Reputation: 2599
I have hard a big time trying to understand how Context stuff really works. I don't really need this now, but I am sure I will need this soon...
EXAMPLE
I made an app called ave
and a library (itself an app) called xvf
with several activities each. Most of them give info through a Toast, so I have everywhere the same method:
public void info(String txt) {
Toast.makeText(getApplicationContext(), txt, Toast.LENGTH_LONG).show();
}
Now I thought to put that method as a class in the library, and call it from everywhere, both from the app classes and the library classes. I do not want to pass the context, like info.show(context, String)
, I want the class info
to infer where the context is when it is being called.
So I made a class called info
:
package com.floritfoto.apps.xvf;
import android.app.Activity;
import android.content.Context;
import android.widget.Toast;
public class info extends Activity{
private Context context;
public info() {
super();
context = (Context)getApplicationContext();
}
public void show(String txt) {
Toast.makeText(context, txt, Toast.LENGTH_LONG).show();
}
}
Then, on the calling activity, I just create an instance of info, and do info.show(String)
. This works.
Problem is that it seems too expensive for mee to extend Activity
just to get the context...
Which is the correct way of doing what I want? It would be even better to do a info(String)
thing... Remember, you are not allowed to make a constructor info(Context, String)
, that's cheating.
Upvotes: 0
Views: 173
Reputation: 30168
I guess it's working by sheer blind luck.
You can't instantiate a proper Activity with new
, you have to let the Android framework do that. In this case it's working because you're getting the Application context, which I guess it figures out by package owner.
In reality, an Activity
is itself a Context
(it extends it) so you could use this
when showing a Toast. If you tried to do that in your info
class I imagine it would fail. Anyway, like Eric pointed out, if you need a Context
in a library class (that's not a proper Activity), you need to pass it in as a parameter to use it.
Upvotes: 2