Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an Object accessible by all Activities in Android

Tags:

android

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:

  1. Create Array in Activity 1
  2. Access same Array in Activity 2 and 3
  3. ???
  4. Profit.
like image 662
A. Steenbergen Avatar asked Sep 01 '11 12:09

A. Steenbergen


People also ask

Can we create object of activity in Android?

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.

What is an activity which method is implemented by all subclasses of an activity?

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.

How do I pass model data from one activity to another in Android?

We can send the data using the putExtra() method from one activity and get the data from the second activity using the getStringExtra() method.

What is MainActivity Java in Android?

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!


1 Answers

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

like image 176
Nic Avatar answered Sep 24 '22 00:09

Nic