Not that complicated of a question today:
Is there a way to get the ApplicationInfo in a static method?
No.
To get to ApplicationInfo you need instance of Context, which you get via and instance of Application or Activity.
So, normally you'd do:
ApplicationInfo appIngo = this.getPackageManager().getApplicationInfo("your.app.package.name", GET_META_DATA)
where this is and instance of Context, either Activity, Service or Application.
You can inherit your your application class from Application
public class TestApplication extends Application
create private static instance variable inside this class
private static TestApplication instance = null;
instantiate it in onCreate method:
instance = this;
write access method
public static TestApplication getInstance() {
return instance;
}
From any place you can call
TestApplication.getInstance().getApplicationInfo()
Same way you can get ApplicationContext.
Related
I have a class that's inputting some data into SharedPreferences.
private static Context context;
context = MainActivity.getContext();
sp = (SharedPreferences) context.getSharedPreferences("currentData", Context.MODE_PRIVATE).edit();
SharedPreferences.Editor editor = sp.edit();
editor.putString("name", placeName);
editor.apply()
I set the context using a method in my MainActivity class:
public static Context getContext(){
return context;
}
However I keep getting a null object reference. Tried multiple solutions from stack overflow and can't overcome the issue.
Why is context returning null?
This is because MainActivity.getContext() is null try passing the context from MainActivity to your class.
public Context context;
public YourClass(Context context) {
this.context= context;
}
In MainActivity init it like this:-
YourClass yours = new YourClass(MainActivity.this);
And also avoid using static contexts it might cause memory leaks !!
Context is an abstract class whose implementation is provided by the
Android system
Context is provided to any Activity by the android system during runtime (Activity indirectly extends Context). You are trying to get Context from MainActivity class via static method, which will not work and will always return null:
context = MainActivity.getContext();
You should always get Context from an instance of Activity, not the class itself. You can do this easily by passing an instance of your current Activity to the constructor of your class. Then, you call getContext() on an INSTANCE of that Activity, not the Activity class itself.
Also, wanted to mention that your code is mostly anti-pattern. You should never store Context in static variables. I'd recommend you read more about Activity lifecycle in android and Context - these are fundamental knowledge.
You can get context statically throughout the application
please try below code:
In the Android Manifest file, declare the following.
<application android:name="com.xyz.MyApplication">
</application>
Use this class
public class MyApplication extends Application {
private static Context context;
public void onCreate() {
super.onCreate();
MyApplication.context = getApplicationContext();
}
public static Context getAppContext() {
return MyApplication.context;
}
}
Now you can call MyApplication.getAppContext() to get your application context statically.
You are getting the context from a static method in the class, that mean that method is called before the class is actually initialized. If there is no actual instance of the activity or if the OS haven't provide with context to the activity, then is null. The Activity has access to the contexto but after the Android underlining management initialized it, the class won't have the context by it self because it is there, if you notice Activities are never instantiated using the constructor because Android does it for you.
If you want to use a static method to having a nice syntax then the static method should be inside the class that use the shared preferences and should be passed from the activity, during any method of the Activity life cycle or when the user interacts with the ui (those listeners are set on the Activity life cycle).
class MyPreferences {
static void save(String toSave, Contex context) {
//TODO your operation here
}
}
And your activity:
public class MainActivity extends AppCompatActivity {
//Below is pseudo code, be careful on doing this precisely in the activity
#Override
onCreate() {
//TODO call super and setContentView
MyPreferences.save("foo", this);
}
}
It seems your problem is you are trying to make the other class to use the Activity, but in Android is the Activity that uses other classes
I have access to application context but not to application. I want to get the application (so I can get all running activities), but couldn't find a way to do so. Is there an existing API to get application from application context or I will have to override getApplicationContext for that?
No, there's no such API out of the box. However, you can either get application context and cast it to Application object, or Extend Application class, and make it a singleton so you can grab an instance of it from everywhere.
public class MyApplication extends Application {
private static MyApplication singleton;
// Returns the application instance
public static MyApplication getInstance() {
return singleton;
}
public final void onCreate() {
super.onCreate();
singleton = this;
}
}
I am stuck in a problem. I am creating a helper class that needs to be Singleton. And that class has a global context variable. I am not able to do this since context is available only from onCreate and this Singleton instance is created much before since it is static.
Can someone help me on how to solve this issue. Context is needed for the Singleton instance finally.
public class Helper {
private static Helper sHelper = new Helper() ;
private Helper () {} ;
public static Helper getInstance() {
return sHelper;
}
public boolean doSomething() {
mContext.getContentResolver;
return isDone;
}
}
You can set the context to be you ApplicationContext.
You can create an Application class and implement something like:
yourSingletonClass.getInstance().setContext(this);
This call should be in you application class under the onCreate method.
For more information try this docs:
Android - Application class
You just need to pass the following context to your helper class.
getApplicationContext()
You need pass the context trougth your construct helper class:
getApplicationContext()
I have created a custom application class like this:
class A extends android.app.Application{
public String abc = "xyz";
}
And I have a simple java class
class B {
private appContext;
// This constructor is called from activity.
B(Context ctx){
this.appContext = ctx;
}
private void foo(){
// want to access Class A's abc String vairable Here...HOW TO DO THAT?????
}
}
How to access Class A's abc String vairable in foo method.
You can get the Application class with getApplicationContext from Context with the good casting
((A) this.ctx.getApplicationContext()).abc;
The Application class in Android is a singleton and therefore so is your derived class. Android will create just one instance of your class A when it starts your application. Just change
class A extends android.app.Application {
public String abc = "xyz";
}
to
class A extends android.app.Application {
public static String abc = "xyz";
}
and you can reference it from anywhere like this:
String foo = A.abc;
Instead of passing a Context, try passing an instance of the Application class instead.
Something like:
class B {
private Application app;
// This constructor is called from activity.
B(Application ctx){
this.app = ctx;
}
private void foo(){
app.abc; //Do what you want
}
}
And call B like:
B b = new B(getApplication());
Make sure that this is in onCreate() or later.
Looks like you are already passing the application context as a parameter and initializing it in the constructor. So all you have to now is to use the context variable to access abc of A like the following way: ((A) this.appContext).abc;
I have a class that needs to obtain a reference to it's application's AssetManager. This class does not extend any sort of android UI class, so it doesn't have a getContext() method, or anything similar. Is there some sort of static Context.getCurrentApplicationContext() type of method?
To clarify: my class is intended to be used like a library, for other applications. It has no associated AndroidManifest.xml or control over the context which is calling it.
Create a subclass of Application, for instance public class App extends Application {
Set the android:name attribute of your <application> tag in the AndroidManifest.xml to point to your new class, e.g. android:name=".App"
In the onCreate() method of your app instance, save your context (e.g. this) to a static field named app and create a static method that returns this field, e.g. getApp():
This is how it should look:
public class App extends Application{
private static Context mContext;
#Override
public void onCreate() {
super.onCreate();
mContext = this;
}
public static Context getContext(){
return mContext;
}
}
Now you can use: App.getContext() whenever you want to get a context, and then getAssetManager() (or App.getContext().getAssetManager()).
I am not sure of the best answer to the OP question. However, I do know that you have to be very careful when using a static context as suggested in Android developer resources:
In the onCreate() method of your app instance, save your context (e.g. this) to a static field named app and create a static method that returns this field, e.g. getApp():
Using static contexts can leak to leaked memory issues, especially if the static context is used for references to views.