How to get my activity context?

AndroidAndroid Context

Android Problem Overview


I don't really get the idea behind how this whole thing works really, so if I have some class A that need the context of a class B which extends Activity, how do i get that context?

I'm searching for a more efficient way than giving the context as a parameter to class A constructor. For example if class A is going to have millions of instances then we would end up having millions of redundant pointer to Context while we should be able somehow to have just one somewhere and a getter function...

Android Solutions


Solution 1 - Android

Ok, I will give a small example on how to do what you ask

public class ClassB extends Activity
{
  
 ClassA A1 = new ClassA(this); // for activity context

 ClassA A2 = new ClassA(getApplicationContext());  // for application context. 

}

Solution 2 - Android

You can use Application class(public class in android.application package),that is:

> Base class for those who need to maintain global application state. > You can provide your own implementation by specifying its name in your > AndroidManifest.xml's tag, which will cause that class > to be instantiated for you when the process for your > application/package is created.

To use this class do:

public class App extends Application {

	private static Context mContext;
	
	public static Context getContext() {
		return mContext;
	}
	
	public static void setContext(Context mContext) {
		this.mContext = mContext;
	}

	...

}

In your manifest:

<application
        android:icon="..."
        android:label="..."
        android:name="com.example.yourmainpackagename.App" >
                       class that extends Application ^^^

In Activity B:

public class B extends Activity {

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sampleactivitylayout);
		
		App.setContext(this);
                  ...
		}
...
}

In class A:

Context c = App.getContext();

Note:

> There is normally no need to subclass Application. In most situation, > static singletons can provide the same functionality in a more modular > way. If your singleton needs a global context (for example to register > broadcast receivers), the function to retrieve it can be given a > Context which internally uses Context.getApplicationContext() when > first constructing the singleton.

Solution 3 - Android

The best and easy way to get the activity context is putting .this after the name of the Activity. For example: If your Activity's name is SecondActivity, its context will be SecondActivity.this

Solution 4 - Android

you pass the context to class B in it's constructor, and make sure you pass getApplicationContext() instead of a activityContext()

Solution 5 - Android

You can create a constructor using parameter Context of class A then you can use this context.

Context c;

A(Context context){ this.c=context }

From B activity you create a object of class A using this constructor and passing getApplicationContext().

Solution 6 - Android

If you need the context of A in B, you need to pass it to B, and you can do that by passing the Activity A as parameter as others suggested. I do not see much the problem of having the many instances of A having their own pointers to B, not sure if that would even be that much of an overhead.

But if that is the problem, a possibility is to keep the pointer to A as a sort of global, avariable of the Application class, as @hasanghaforian suggested. In fact, depending on what do you need the context for, you could even use the context of the Application instead.

I'd suggest reading this article about context to better figure it out what context you need.

Solution 7 - Android

In Kotlin will be :

activity?.applicationContext?.let {
         it//<- you context
        }

Solution 8 - Android

The MainActivity class has those properties you can use:

  • applicationContext
  • baseContext
  • this

See here for differences: https://stackoverflow.com/questions/10347184/difference-and-when-to-use-getapplication-getapplicationcontext-getbasecon

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOfek RonView Question on Stackoverflow
Solution 1 - AndroidGanView Answer on Stackoverflow
Solution 2 - AndroidhasanghaforianView Answer on Stackoverflow
Solution 3 - AndroidJohn Alexander BettsView Answer on Stackoverflow
Solution 4 - AndroidSharkView Answer on Stackoverflow
Solution 5 - AndroidHelal KhanView Answer on Stackoverflow
Solution 6 - AndroidThomasView Answer on Stackoverflow
Solution 7 - AndroidSerg BurlakaView Answer on Stackoverflow
Solution 8 - AndroidRonen FestingerView Answer on Stackoverflow