Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass context from activity to activity?

I have a main activity, and it summons another activity to display some data.

I have a private database helper object that I use throughout the main activity code. Is there a way to pass the context of my main activity to my sub activity in an elegant way? (ie, from subclass, something like getCallingActivityContext())

I could always create new database helper objects.

like image 992
Tony Ren Avatar asked Oct 12 '11 03:10

Tony Ren


People also ask

How do you pass context as another activity?

You can create a method like setContext(Context context) in your DataBase Helper class to pass your context from your activity. Show activity on this post. You can get the context if you do getApplicationContext(); from your activity and pass that to your DBHelper class.

How do you pass a value from activity to activity?

This example demonstrates how do I pass data between activities in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.

Can application context be passed using intent to another activity?

There is no way to pass the context to the target activity using Intent.

How do you pass context?

It is used to return the Context which is linked to the Application which holds all activities running inside it. When we call a method or a constructor, we often have to pass a Context and often we use “this” to pass the activity Context or “getApplicationContext” to pass the application Context.


2 Answers

Extending the Application class helps you to allow declare/access global variables. You can set your variables from any activity to ApplicationContext and access it from other activity without using bundle.

How to declare global variables in Android? will help you.

like image 183
gtiwari333 Avatar answered Sep 30 '22 20:09

gtiwari333


For your case, I would recommend you to extend instead the Application class. All your activities have access to the Application context by calling getApplicationContext() at any time. Check here the 1st answer for an example.

like image 25
Jan S. Avatar answered Sep 30 '22 20:09

Jan S.