Android; Implementing global state; share data between Activities and across your application

If your developing an Android application, chances are you will have multiple activities that perform various tasks. One of my first questions when I was investigating Android, was how can I pass data between my Activities? Moreover, how can I retain some form of state, globally throughout my application, so I can dynamically pass data without having to persist to a datastore between Activities.

The solution; Use the applications Context

Firstly, you should create a new class that will behave as our global object, for example :

package com.jameselsey.domain;

import java.util.ArrayList;
import java.util.List;
import com.google.android.maps.GeoPoint;
import android.app.Application;

/**
* This is a global POJO that we attach data to which we
* want to use across the application
* @author James Elsey
*
*/
public class GlobalState extends Application
{
private String testMe;

public String getTestMe() {
return testMe;
}
public void setTestMe(String testMe) {
this.testMe = testMe;
}
}

The above class declares one String, with accessor methods. Soon we will see how this object will be available throughout the application. You can add anything you want onto this object, in my application I have a List of other domain classes that I wanted to use elsewhere in my application.

Right, now that you have your global class defined, you need to specify this in your AndroidManifest file, otherwise the application won’t know where to find this class, and you will get a ClassNotFoundException

Locate your application tag, and add this into it :

android:name="com.jameselsey.domain.GlobalState"

It must reference your fully qualified global state class

Now you have it set, your ready to start putting data in, and pulling data out, use the following

// Set values
GlobalState gs = (GlobalState) getApplication();
gs.setTestMe("Some String");</code>

// Get values
GlobalState gs = (GlobalState) getApplication();
String s = gs.getTestMe();

And thats it! Off you go!

Loading Facebook Comments ...

24 thoughts on “Android; Implementing global state; share data between Activities and across your application

  1. I’ve seen several snippets like this, and have run into the same barrier… The application crashes when I try to access the application object (“GlobalState gs = (GlobalState) getApplication();”) with a log report like the following.

    java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=2, result=3, data=Intent { (has extras) }} to activity {com.mjh.Login/com.mjh.Login.Initialize}: java.lang.ClassCastException: android.app.Application

    This snippet, like all others, simply say to alter your Application tag in the manifest. I have done so to the best of my ability, and still it crashes…HELP!!!

    I want the app to start with the Initialize activity. It will then use Login for a result. If the result is a proper login, it should then start the Home activity. Everything works perfectly until I call getApplication()

    Here’s my Application tag in its entirety:

    I don’t see where I’m going wrong and it’s driving me nuts…

    • Hi Michael,

      Are you still having trouble with this? What version of droid are you using?

      Did you copy my example exactly? If you can zip up your app and send it to me : james dot elsey at gmail dot com, then I’ll open it up and see if I can spot the failure.

      I didn’t encounter any issues when doing this, so not sure why you’re having so much trouble

      Regards

      • I have to store ArrayLists of Objects in the share data. I want to release references to those ArrayLists at some point and call gc(). Call a cleanup() function before my application is killed or destroyed.

  2. I am a C programmer and I am very new to Android and Java.


    Hunt:

    I have to store ArrayLists of Objects in the share data. I want to release references to those ArrayLists at some point and call gc(). Call a cleanup() function before my application is killed or destroyed.

    • Best to have it in a separate class, so you can define that class in the manifest and extract global state functionality from activities.

  3. But how does the application context call the activity? If you keep a reference to the activity in the application, then you leak the activity, which is the reason for using the application in the first place. The example I have in mind is a thread pool that is persisted in the application, but whose thread procs need to post messages to the UI thread….

  4. Hmm.. what is the advantage of extending Application rather than using a simple singleton class to do the same? Especially for something simple as this example illustrates… the android documentation itself even states:

    There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.

    (http://developer.android.com/reference/android/app/Application.html)

    • At this point I’m not aware of any real benefits of either method (although I’m sure there are various pros/cons) I was purely demonstrating one solution of having global state :)

  5. Hey James,

    Thanks a lot for this. It works like a charm. You have no idea how many tutorials I’ve done and how much I had to google until I came across this.

    Thanks!

Leave a Comment


six × 1 =