Android getApplicationContext() outside Activity and Application - android

How I can get application context outside activity and without extending application class.
class A{
public static B b = new B(App context here);
}
Objetc b must be as a field

No you can't get context without extending Application or Activity by the given example. All that you can do is to have a static method in a class (extends Application) that would return context and then pass that method as a parameter to your B().
BTW, I did not get your intention of doing this. Can you detail out what exactly you wants to do.
Thank you

It is not possible.
If it were, it would mean that any Java class would be able to access an android.content.Context instance, even when is not related to anything in Android, for example, a Java EE application.
What you can do, is, have a static reference to a Context (an Application or an Activity) in a centralized place inside your app, but I wouldn't recommend it because it would cause multiple memory leaks.

Related

Saving a static Context variable in Application class

I've wondering if it's okay to do this: whenever we pass a Context variable around, could we just get a singleton reference from the Application class instead
For example here is a subclass of Application class with a single static variable pointing to its own instance
public class App extends Application {
public static mApp;
#Override
public void onCreate(){
mApp = this;
}
}
Then when we need to pass a Context to a method from somewhere, can we just do
foo(App.mApp);
Isn't it okay to treat Context as an application variable?
Well it depends on the context in which you are using it. Many times a context is meant to keep hold of things until it's lifescope is complete and then allow garbage collection to take back whatever it was owning.
Other times the context needs to be an activity to handle life cycle call backs such as onNewIntent or onActivityResult.
Keeping a static instance in the parent is just a shortcut to avoid having to getApplication() and cast it as your type of application. I typically make a method for MyApplication.getApplication().doSomething which will return it's own reference of itself as opposed to ((MyApplication)getApplication()).doSomething
Just seems cleaner for coding purposes. But I would be very leary of using the application context everywhere you need a context, it will come back to bite you eventually.
But yes you can certainly store yourself as a static variable to be shared, I do it in most applications, but typically for a specific shortcut purpose of clean maintainable code, not for cheating on getting context from various crevices.

Is it safe to use reference to the Application where Context is required?

As it stands we need to pass a Context in many places within Android application. I'm wondering how safe it is to use a static variable which refers to the Application class instance in such places? For example, I have a static method in one of my Activities and I can't use this (as Activity) or something because the method is static, so I'm guessing to use the Application.instance reference which is initialized on each application start. Is it ok you think? Thanks a lot.
It depends on your method and what you are trying to do with the Context. If you want to get resources like a String or Drawable from your app, then it is save to use the Application Context. But if you want to display a Dialog, then you definitely should use the Activity Context.
As far as I know, for a Toast you can use the Application Context as well.

Static Utility class with Context/Activity - Android

Over the development of an Android app I've come to a collection of utility-type methods that I have put into a static class. All these methods are used across multiple Activities and most of them do not require any information from the calling Activity.
However, I now have some methods that require the Context of the Activity and one that requires the Activity itself. Let me exemplify some of them:
getDeviceNaturalOrientation() - Uses an Activity's
getWindow().getWindowManager().getDefaultDisplay() to access the
displays rotation, width, and height to determine the device's
natural orientation.
getDeviceOrientation() - Similar to the above but to get the current
orientation
createFile() - Uses the Context to to access some resources (strings) and to
create and show some Toasts
Now, my big questions regarding this Utils class are:
So far, each function takes a Context parameter which I pass from whatever Activity I'm on, but would it be OK to create a static Context or Activity variable in the Utils class and set it at the beginning of each Activity (like in onCreate)? This variable would be used in whatever functions require a Context or Activity instance.
Assuming the above is not recommended, is it OK to pass an Activity parameter to a method or is there a reason to only pass an Activity as Context? The methods I use for the device orientation functions above are specific to Activity objects, not Context, so either I pass as Activity or pass as Context and cast into Activity (the latter sounding like a terrible idea).
Also, I am very open to the idea that this Util class may not be the way to go for these methods that require Context/Activity, so I would welcome alternatives that would still prevent having copies of these methods in each activity class that uses them.
1)A static link to a context is likely to cause a memory leak. It means that a reference to the Activity will be kept around in the static variable even after its destroyed, so all of the memory of the activity and all its views will remain valid and not be cleaned by gc. You can do this, but you have to be careful to null out the variable when done. Its better just to avoid it.
2)Its a little bit awkward to pass the activity as an Activity, but no technical reason not to. At that point we're arguing over code cleanliness/maintainability. And there are times where the non-clean solution is just easier. Of course in the cases above I'd rather pass the orientation/display/Resources objects to the function than pass the entire context or make special accessors.
I think following design should be fine when you call from Activity
MyUtility utility=new MyUtility();
utility.getDeviceNaturalOrientation(this);
utility.getFile(this);
And you can define these function like
public int getDeviceNaturalOrientation(Activity activity){
//code
return some_oreientation
}
and like this
public File getFile(Context context){
//code
//return file handler
}
Activity is the subclass of Context so you can even change the design to following
MyUtility utility=new MyUtility(this); //this refer to Activity
utility.getDeviceNaturalOrientation();
utility.getFile();
As long as you pass activity you are fine but if you do following from your activity you will get error from first method call
MyUtility utility=new MyUtility(getApplicationContext());
utility.getDeviceNaturalOrientation(); //will throw exception
utility.getFile();
And, yes first idea is not a recommended way.
I would suggest you to send a WeakReference of your Activity or getApplicationContext() (for those works which can work using it) and don't use static method because it cause memory leaks. Read Developer blog also

What is the purpose of Application class in Android

What exactly is the purpose of Application class.
what are the benefits of extending it to a custom subclass
Why use it ?
Can global variables be stored in any other class achieve same goal as Application ?
Nice question !
Your application is a context that is always running while your activities and services are running.
It is also the first context to be created and the last to be destroyed.
Thus, it surrounds the life cycle of your app.
You can use the application class as a way to share data or components (for dependency injection for instance). For instance if you want to share a singleton between activities, you can create the instance in the application class and provide a getter, then all other contexts can get the singleton via
((cast to your class)getApplicationContext()).getFoo();
There may be some use cases where you need to do stuff before even your first activity is launched, then do it in the onCreate method of the application class.
On the other hand, you should never relie on the onDestroy method of the Application class, as it is not always called. There is no contract for that on Android.
But this is rare and, usually, you don't need to override the application class though. Dependency injection can be achieved in other ways by RoboGuice or Dagger for instance.
Two things makes this Class very useful:
Application class is instantiated before any other Activity.
It holds the Application Context
Context brings a host of resources for us: we can figure out some device properties, load some resources, initiate a SQLite database etc, etc.
All of this happens before any Activity loads, and all of this is globally available to the Activities.
Simple example of what I mean:
public class App extends Application{
private static Resources sResources;
//--I want to load strings resources from anywhere--
public static String loadStringResource(int resID) {
return sResources.getString(resID);
}
#Override
public void onCreate() {
super.onCreate();
sResources = getResources();
//---I want to load all preferences when my app starts---
PreferenceManager.setDefaultValues(this,R.xml.prefs,false);
}
}
Extending the Application class allows you to integrate into the application's lifecycle.
This is also useful to store global application-level information (though it's usually good to keep your activities 'independent')
The Application class is aware of the Application Context and is loaded when your app is loaded so it holds the proper callbacks for the application lifecycle before your activity starts. You most likely would not want to extend this class.
From the API docs:
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.
http://developer.android.com/reference/android/app/Application.html

Pattern for access to conttext from java class (that it isn't activities)

In my android project I have some activity classes, and also simples java classes. There are some of them are independent of contextes and views totally, but in others duly I need it for to access a particular method of context.
I have read about it, and some people says they pass the context of some activity to every class that need its methods; others that pass a view and then get the context or that this classes have to extend of Activity... ¬¬
But for example, I have a class where it only calls once a method of context like:
getSharedPreferences(configNameFile, 0);
getString(R.string.text);
...
Therefore I would like to know what pattern do you use to do this always.
My personal favorite ways to do this is:
Dependency injection
using RoboGuice
or
Make sure you don't need the context
If possible, try to avoid using the context in other files then your activity. If it is really needed, I write a wrapper most of the time. E.g. for Settings, I write a Settings interface that is able to do it with shared preferences. Whenever you want to change your settings implementation later, it is easily done by swapping the implementation of your interface. If you really need it, I'd prefer using a static Application context
Also, you could make that method accept a Context paramerter, for example:
public void getPrefs(Context context){
context.getSharedPreferences(configNameFile, 0);
context.getString(R.string.text);
}
Then in your Activity pass the current context to it:
public void getPrefs(this);

Categories

Resources