jochot
jochot

Reputation: 167

Working with Android Context in non-Activity Class

I often have the Problem, that I cannot use something because of the Context it needs.

For example, if you have a Toast you want to use in a Class for something, you need Context but you cannot use any context, because you are not in an Activity.

Now what I did was, I gave that Class I made a variable "context" which is set in the constructor, but I don't really think this is right.

So how do I handle the context in a non-Activity Class?

Thanks in advance :)

Upvotes: 3

Views: 3815

Answers (4)

skynet
skynet

Reputation: 726

Never keep a reference to context as a member variable or as a static variable, as it might lead to memory leaks as it becomes difficult for the GC to collect the references.

Since you are using context in a non activity class, I assume that class to be some kind of a helper class with static method blocks.

For eg :

public class ToastMessageHelper {

   public static void showToast(Context context) {
       Toast.makeText(context, "Hello",Toast.LENGTH_SHORT).show();
   }

}

It is better to pass context as a parameter to the methods which require the context to execute.

Now, you can simply call,

ToastMessageHelper.showToast(context);

in your activity or a fragment. Hope this helps!

Upvotes: 3

BlackHatSamurai
BlackHatSamurai

Reputation: 23503

If you aren't in an activity, you can always use getApplicationContext() which will return the context for the app.

Upvotes: 1

Ailton Ramos
Ailton Ramos

Reputation: 106

A sophisticated way to use context in a non-Activity class is the ContextWrapper.

You can read a little bit about this here:
Best practice to pass Context to non-activity classes?
or here
http://itekblog.com/android-context-in-non-activity-class/

You could also use a variable "context" or pass by parameter in a static method and you should be fine, being in mind you can have some issues with this practice.

Upvotes: 0

Alberto Méndez
Alberto Méndez

Reputation: 1064

Yes you are right, you usually pass the Context to the required object or class which may require it, sometimes you pass it in the constructor, but knowing that the context may change sometimes is better to pass it right in the method. It is up to the developer choose the right scenario.

It is true that in some situations you could need another way to get or pass the context, but usually passing it in the constructor or methods is enough

Upvotes: 0

Related Questions