I store strings obtained from parsing XML in an ArrayList. There are开发者_Python百科 many such arrayLists. How do I make these ArrayLists available to all the activities in the application so that I don't need to pass arrays to the activities using intents.
I don't think a static field is what you want here. You haven't mentioned where this xml is coming from, but I'm assuming you mean a string array specified in a xml file included in your app. In that case, you'll need to get a handle to the Resources object and for that you'll need a Context.
The Application object is always around and is accessible from all of your Activities. I would create and store these global ArrayLists there. Since it sounds like you have a bunch of them, could have a Map of ArrayLists and a function in your Application class that takes the name of the ArrayList you want and returns the appropriate ArrayList from the Map.
public class MyApp extends Application {
private Map<String, ArrayList<String>> mLists=new HashMap<String, ArrayList<String>>();
public void addList(String key, ArrayList<String> list) {
mLists.put(key,list);
}
public ArrayList<String> getList(String key) {
return mLists.get(key);
}
}
Extend Application and have it hold your data. Then in your intent you do
((MyApplication)getApplication()).getData();
Avoid making static
variables. It's quick and painless, but it becomes messy real quick.
Check this earlier question
There's a good write-up of various ways of doing this in the Android Application Framework FAQ.
Having 'many' lists and making them static is not very efficient. You could use content providers that are more efficient I think.
You are best defining a handler to pass data between activities.
A good explanation of use is in this stackoverflow post
How to access original activity's views from spawned background service
and android dev write up is here
http://developer.android.com/reference/android/os/Handler.html
You would define a handler on your main thread with the ArrayLists you want to make available.
精彩评论