I'm trying to create an ArrayList of Data containing Objects (Like a list of Addresses and properties (pretty complex)) and am wondering: How can I make an Object accessible (and editable) by all Activities and not just the one it was instanciated in?
Basically this:
You cannot just create objects of Activities by using: MyActivity activity = new MyActivity(); as you would with normal Java classes. All Activities in Android must go through the Activity lifecycle so that they have a valid context attached to them.
An activity represents a single screen with a user interface just like window or frame of Java. Android activity is the subclass of ContextThemeWrapper class. The Activity class defines the following call backs i.e. events. You don't need to implement all the callbacks methods.
We can send the data using the putExtra() method from one activity and get the data from the second activity using the getStringExtra() method.
The main activity code is a Java file MainActivity.java. This is the actual application file which ultimately gets converted to a Dalvik executable and runs your application. Following is the default code generated by the application wizard for Hello World!
The easiest way to do this is by creating an Singleton. It's a kind of object that only can be created once, and if you try to access it again it will return the existing instance of the object. Inside this you can hold your array.
public class Singleton {
private static final Singleton instance = new Singleton();
// Private constructor prevents instantiation from other classes
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
}
Read more about singleton: http://en.wikipedia.org/wiki/Singleton_pattern
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With