I'm using extending application class on Android to share my data across the entire app.
I can use getApplication()
method from all my activities.
However, there are certain custom helper classes I created; for example, an XMLHelper
class which does not inherit from any activity / service class.
Here the getApplication()
method is not available.
How do I sort this out and what are the best design practices to solve this?
The getApplication()
method is located in the Activity
class, that's why you can't access it from your helper class.
If you really need to access your application context from your helper, you should hold a reference to the activity's context and pass it on invocation to the helper.
The getApplication()
method is located in the Activity
class, so whenever you want getApplication()
in a non activity class you have to pass an Activity
instance to the constructor of that non activity class.
assume that test is my non activity class:
Test test = new Test(this);
In that class i have created one constructor:
public Class Test
{
public Activity activity;
public Test (Activity act)
{
this.activity = act;
// Now here you can get getApplication()
}
}
Casting a Context object to an Activity object compiles fine.
Try this:
((Activity) mContext).getApplication(...)
Either pass in a Context (so you can access resources), or make the helper methods static.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With