Using getResources() in non-activity class

ssk picture ssk · Oct 5, 2011 · Viewed 180.9k times · Source

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);

Answer

LuckyLuke picture LuckyLuke · Oct 5, 2011

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