Hi i am trying to understand the use of context though i couldn't. Following is a program using context. My question is what is the significance of " context = class.this " ?
class public VcardActivity extends Activity
{
String Vcard = "vcard";
Context context;
}
public void onCreate ( Bundle bn )
{
super.onCreate(bn);
setContentView(R.layout.main);
context = VcardActivity.this;
}
Your current code doesn't show the use of context. It shows that the Activity is a context.
TextView someText=new TextView(context);
This code of mine shows, I am passing a context into the constructor of a TextView in order to make this object. The reason is, this object needs to know the information, state of the current context, and this is the reason why many views, classes, helpers needs a context.
context = VcardActivity.this;
in your code you are having your activity object to assign to the Context context. This works because Activity class inherits from Context and many classes needs a Context to create it.
In your case, the field context is not necessary at all. It rather is used as a shortcut to VcardActivity.this here. You could remove it without any problems and use VcardActivity.this or even only this where you used to use context.
You don't need to create a separate Context variable inside of an Activity. You use Context for certain objects/methods that need to know what is starting them. Activity already has a Context so you don't need to create it. If you need to use Context within an Activity, say when creating an Intent you can just use ActivityName.this or here VcardActivity
See this SO answer for a good explanation of using which kind of Context when.
Context Docs
Related
I had an Android application(MyApp, say) that used ApplicationContext extensively. The ApplicationContext was made available via a class that extended Application.
class MyApp extends Application {
static Context mContext = null;
public void onCreate() {
mContext = getApplicationContext();
}
public static Context getContext() {
return mContext;
}
}
I would like to convert this application to a library and use it in another application ( AnotherApp, say). Now I see that AnotherApp already has a similar class that extends Application and gives its context everywhere within itself. When I move MyApp as a library into AnotherApp, my code will not be able to get ApplicationContext anymore - as only one class can be declared in Manifest (android:name=".AnotherApp")
What is the best way to make application context available within library? I do not mind making extensive code changes, but would like to know options I have - other than passing context to every api in my library.
A library should never use the getApplicationCOntext it is meant for the main program.
you can pass the context using a function or save it into a public static variable in your class in the beginning.
Note about code design
This completely depends on how you want to use the library, will the functions be used in the main app ? Will the activity be directly called ? and a bunch of other code design things like that.
If you want two activities sometimes the best way it to make them into separate applications and make one call the other using an Intent. Like how google maps and other inbuilt services are used.
If you want to use your library's function in the main application, you should not be creating an activity at all. Rather you should make an abstract class that the user can inherit from and use your class through.
I have done similar stuffs in my Application.
Its true you will not able to get context in your library
You will have context of only AnotherApp
If you want to use Context in your library in that case you need to have some method which can pass your AnotherApp's context to your library.
For example
class MyApp extends Application {
static Context mContext = null;
public void onCreate() {
mContext = getApplicationContext();
objecofYourLibClass = new MyApp();
objecofYourLibClass.yourMethod(mContext);
}
}
Now you will able to use context in your Library.
Hi i'm trying to pass a value by using Global Variable. I have created a class file where it is extended to Application and then add it on my Manifest.
public class MyApplication extends Application {}
After that I had created an Adapter Class which is extended to BaseExpandableListAdapter, I've search on how to set and get the global variable i've created and found this
((MyApplication) getActivity().getApplication()).setMy_id(my_id);
and to be able to get the value I use this
Integer my_id = ((MyApplication) getActivity().getApplication()).getMy_id();
In my Fragments, I can use my getMy_id() method but when putting it inside the BaseExpandableListAdapter, I'm having an error in getActivity(). I already tried using this but still it says Cannot resolve method getApplication(), is there any other way to get the value of my global variable.
I'm doing this because I'm trying to use Cursor for my ListView. I wanted to create a Expandable ListView where the data is from my database and my Cursor have a parameter for it's WHERE condition where my data in my global variable will be used.
The reason why I'm using it as a global variable because I use this data in different Fragments where it is not static it changes its value depends on the selected item.
Thank you in advance.
You need to have a constructor in your class that extends BaseExpandableListAdapter. The defined constructor should receive a parameters of Context type. Here is the example -
private Context mContext;
public YourExpandableListAdapter(Context context) {
mContext = context;
Integer my_id = ((MyApplication) context.getApplicationContext()()).getMy_id();
}
Now create an instance like this in your activity -
YourExpandableListAdapter ob = new YourExpandableListAdapter(this);
This should work.
I'm not really sure what you're trying to achieve but whatever it is you're doing seems hacky to me! As per answering your question, getApplication() needs a context, so when you do
((MyApplication) getActivity().getApplication())
You are essentially using the activitiy's(getActivity()) context. And you cannot call getActivity() in an Adapter class. Try passing the context of your activity from the activity to the adapter in your constructor, something like.
MyAdapter myAdapter = new MyAdapter(this); //This line will be in your activity, and this will be the instance of your activity
And your adapter constructor would look something like
public MyAdapter(Context context){
//Use this context to get the application instance, something like
Integer my_id = ((MyApplication) context.getApplication()).getMy_id();
}
For Me, all above didn't work. try this:
((MyApplication) context.getApplicationContext()).getMy_id();
I am writing client REST application for Android. Because in my main Activity there is a lot of methods I decided to move rest operations to new class 'RestClient'.
Over there I need application context to execute: Volley.newRequestQueue(CONTEXT HERE); and to create Toasts.
What is the best way to do that?
I believe that making static Context context in Activity and then access it inside class is not the best way.
The safest way is to always pass the Context to any method that needs it, e.g.
public void showToast(final Context context, ...)
so you can call it from an Activity as follows
showToast(this, ...);
I am combining a static code analysis with a dynamic one. I basically create a new activity and set it up as the starting activity. During the run various methods in existing activities should be called.
I can call e.g. onCreate from outside, however, the super call to Activity will fail (or calls to SharedPreferences or other interesting classes) since Android does some initialization stuff when using the intents in order to call an activity (e.g. setting the context). But I need to somehow call methods like onCreate or onPause from outside while giving the target activity a valid context.
In my newly created activity I have got a valid context. I tried to pass it via calling ContextWrapper.attachBaseContext, but there is still a NullPointerException somewhere in Android due a the missing context. Is there some way to hack this somehow into a working state? Using reflection or other hacks would be no problem, since it is for analysis purposes only.
Thank you very much for any tips. I'd be able to modify the analyzed apps in any way to get this working.
However: Using an Intent is no option, since I cannot control which Activity-methods are being called, when and how often. I know that android has not been made for calling these methods directly, but it is not a common use case either :);
I have created a hack, which seems to help (I can get a valid context in the hacked activity). Let's see how far I get using this.
public static void hack(Activity hack, Activity main) {
try {
Field mActivityInfo = getField(Activity.class, "mActivityInfo");
mActivityInfo.set(hack, getClass("android.content.pm.ActivityInfo").newInstance());
Field mFragments = getField(Activity.class, "mFragments");
Field mContainer = getField(Activity.class, "mContainer");
Field mApplication = getField(Activity.class, "mApplication");
Field mWindow = getField(Activity.class, "mWindow");
Class FragmentManagerImpl = getClass("android.app.FragmentManagerImpl");
FragmentManager manager = (FragmentManager) mFragments.get(hack);
mApplication.set(hack, main.getApplication());
mWindow.set(hack, main.getWindow());
Class<?> FragmentContainer = getClass("android.app.FragmentContainer");
Method attachActivity = getMethod(FragmentManagerImpl, "attachActivity", Activity.class, FragmentContainer, Fragment.class);
attachActivity.invoke(manager, hack, mContainer.get(hack), null);
Method attachBaseContext = getMethod(ContextWrapper.class, "attachBaseContext", Context.class);
attachBaseContext.invoke(hack, new HackContext(main));
System.out.println("Hack performed");
} catch (Exception e) {
e.printStackTrace();
System.err.println("Hack failed :(");
}
}
I am trying to generate a notification from a class, Utilities.java, outside of the subclass of Context. I've thought about providing a SingletonContext class and have looked at posts ike this. I'd like to be able to return != null Context object since the notification can be generated at any given time because it is generated from a messageReceived() callback.
What are there downsides to doing something like this:
public static Context c;
public class MainActivity extends Activity{
#Override
public void onStart()
super.onStart()
c = this.getApplicationContext();
}
//other method somewhere outside this class
public Context getContext(){
return MainActivity.c
}
I don't think it would be any different than putting this on the onCreate(), however, it guarantees that the context is up to date when the activity starts.
The Context keeps a reference to this activity in memory, which you might not want. Perhaps use
this.getApplicationContext();
instead. This will still let you do file IO and most other things a context requires. Without a specific reference to this activity.
Maybe you should overwrite the onResume Method.
If you open a new activity, and switch back, the onStart method will not getting invoked.
Android Lifecycle: doc
BTW: I read about problems with ApplicationContext using a dialog or toast, so if you use the context to create on of these you should use your Activity as context.