I am attempting to build an Android application that has two tabs, one for a textField/button and TreeMenu (where each element has a checkbox associated with it) and another for
A singleton class could help solve your problem.
public class GlobalApp {
private static GlobalApp instance = new GlobalApp();
private GlobalApp() {}
public static GlobalApp getInstance() {
return instance;
}
public ArrayList < ClassName > varName = new ArrayList < ClassName > ();
}
Then use in your class like this..
GlobalApp.getInstance().varName
In some of the answers there's a suggestion to put the ArrayList in a singleton, but that doesn't really solve your problem does it? Sure, you'll be able to access it from where ever you like, but it doesn't help you keeping two different fragments, both using the arraylist, in sync.
Start by putting the ArrayList in a singleton as suggested or in your MainActivity. Once that is done you have at least two options for keeping the fragments in sync with the content of the ArrayList:
Make the ArrayList Observable (check ObservableArrayList) and let the Fragments Observe the ArrayList for changes.
Make use of an event bus (like Otto) and let the singleton or MainActivity (depending on where you put the ArrayList) post update events on the bus when the arraylist changes and have the Fragments subscribe to the events.
I had the same issue a little time ago with an ArrayList and other data. In the end I decided to create a class that extends application and that holds all the global data and can be accessed everywhere from the app. Do you want and example?
As John said, when you want to access data in several activities, just create a class that extends Application:
import android.app.Application;
/**
* Application class used to share data between activities.
* @author Longeanie Christophe
*
*/
public class MyApplication extends Application {
//Put your class members here
@Override
public void onCreate() {
//initialize what's needed here
}
//Getters and setters...
}
In all your activities, you can access this class and its data through this instruction:
MyApplication myApp = (MyApplication) getApplication();
Here you go: first be sure you declare it in your AndroidManifest:
<application
android:name="com.example.main.ApplicationClass"
etc..>
<!-- other activities, services etc: -->
</application>
and your class:
public class ApplicationClass extends Application {
private static ApplicationClass THIS = null;
ArrayList<String> list = new ArrayList<String>();
public void onCreate() {
super.onCreate();
THIS = this;
}
public static ApplicationClass getThisInstance() {
return THIS;
}
}