2

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.

Ken White
  • 123,280
  • 14
  • 225
  • 444
pradeep
  • 3,005
  • 12
  • 42
  • 65

6 Answers6

2

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

}

}
jfelectron
  • 1,033
  • 9
  • 6
1

Extend Application and have it hold your data. Then in your intent you do

((MyApplication)getApplication()).getData();
Nathan Schwermann
  • 31,285
  • 16
  • 80
  • 91
1

Avoid making static variables. It's quick and painless, but it becomes messy real quick.

Check this earlier question

Community
  • 1
  • 1
st0le
  • 33,375
  • 8
  • 89
  • 89
0

There's a good write-up of various ways of doing this in the Android Application Framework FAQ.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0

Having 'many' lists and making them static is not very efficient. You could use content providers that are more efficient I think.

Ujwal Parker
  • 682
  • 7
  • 11
0

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.

Community
  • 1
  • 1
rogermushroom
  • 5,486
  • 4
  • 42
  • 68