I have some static xml data that I want to read once and store globally. Initially I simply read the file from an activity into a Map, however, I now need to access the data from multiple activities so I want to avoid reading it from the file from each activity.
I’m using XmlPullParser which requires a context. My problem is that I want to store it into a static variable like so…
public static Map<String,String> myXmlData=getXmlData(???);
but I don’t know how to get the application context in a static way.
public static Map<String, String> getXMLData(Context ctx){
Map<String, String> data = new HashMap<String, String>();
XmlPullParser parser = ctx.getResources().getXml(R.xml.mydata );
...
}
I tried removing the ctx parameter, from the static method above, and calling GetApplicationContext() but the compiler didn’t like that I was trying to make that call from a static method.
Any ideas anyone?
You should extend the Application class on your app. This is the entry point for app-wide resources that need to be initialized.
Application.onCreate will be one of the first things of your application to be executed when the user launches your app.
Since Application extends context, you can get anything you might need to initialize your app ( resources, refereces, system services, etc ).
Here’s a tutorial http://www.helloandroid.com/tutorials/maintaining-global-application-state