Providing data obtained as part of one activity for all activities

I store strings received when parsing XML in an ArrayList. There are many such lists of arrays. How to make these ArrayLists available to all actions in the application, so I don’t need to pass arrays to actions using intentions.

+2
android
source share
6 answers

There’s a good record of various ways to do this in the Android Application Frequently Asked Questions .

0
source share

I don't think a static field is what you want here. You did not mention where this xml came from, but I assume you mean the string array specified in the xml file included in your application. In this case, you need to get a handle to the "Resources" object, and for this you need context.

The application object is always nearby and accessible from all your actions. I would create and save these global ArrayLists. Since it looks like you have a bunch, you 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 corresponding 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); } } 
+2
source share

Extend the application and save the data. Then in your intentions you do

 ((MyApplication)getApplication()).getData(); 
+1
source share

Avoid creating static variables. It is quick and painless, but it becomes messy and fast.

Check this earlier question.

+1
source share

The presence of "many" lists and their static nature are not very effective. You can use content providers that are more efficient, I think.

0
source share

It is best to define a handler for passing data between actions.

Good explanation of usage in this postoverflow post

How to access views of original activity from a created background service

and the entry in android dev is here

http://developer.android.com/reference/android/os/Handler.html

You define a handler in your main thread with the ArrayLists you want to make available.

0
source share

All Articles