I store strings obtained from parsing XML in an ArrayList. There are 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.
6 Answers
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);
}
}

- 1,033
- 9
- 6
Extend Application and have it hold your data. Then in your intent you do
((MyApplication)getApplication()).getData();

- 31,285
- 16
- 80
- 91
There's a good write-up of various ways of doing this in the Android Application Framework FAQ.

- 232,168
- 48
- 399
- 521
Having 'many' lists and making them static is not very efficient. You could use content providers that are more efficient I think.

- 682
- 7
- 11
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.

- 1
- 1

- 5,486
- 4
- 42
- 68