Using getResources() in non-activity class
I am trying to use getResources method in a non-activity class. How do I get the reference to the "resources" object so that I can access the xml file stored under resources folder?
Example:
XmlPullParser xpp = getResources().getXml(R.xml.samplexml);
Solution 1:
You will have to pass a context
object to it. Either this
if you have a reference to the class in an activty, or getApplicationContext()
public class MyActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
RegularClass regularClass = new RegularClass(this);
}
}
Then you can use it in the constructor (or set it to an instance variable):
public class RegularClass(){
private Context context;
public RegularClass(Context current){
this.context = current;
}
public findResource(){
context.getResources().getXml(R.xml.samplexml);
}
}
Where the constructor accepts Context
as a parameter
Solution 2:
Its not a good idea to pass Context
objects around. This often will lead to memory leaks. My suggestion is that you don't do it. I have made numerous Android apps without having to pass context to non-activity classes in the app. A better idea would be to get the resources you need access to while your in the Activity
or Fragment
, and hold onto it in another class. You can then use that class in any other classes in your app to access the resources, without having to pass around Context
objects.