Available for hire
Maintain State of an Android Application

I’ve recently been getting involved in a little bit more android application development, and I was curious on the different ways state can be maintained in an android application on screen rotation, or between activities. Here is the design pattern I’ve found most effective.

Each android application extends from the Application, it shares various characteristics of a Singleton, but fundamentally isn’t a Singleton in the traditional sense. There are various discussions on stackoverflow discussing the finer semantics of this, but we’ll just accept that this works, and begin.

By extending the Application class we can store application specific information.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Game extends Application {
  private int score = 0;
  private boolean gameLoaded = false;

  public Game() {
    if(!gameLoaded) {
      // Init your game, build isometric tile maps, or start to define your level
      gameLoaded = true;
    }
  }

  public void incrementScore() {
    score++;
  }

  public int getScore() {
    return score;
  }
}

Then in your Activity you can simple call getApplicationContext() which returns a game object to store state, and interact.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class MainActivity extends Activity {
  View activityMain;
  TextView message;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Game state = ((Game) getApplicationContext());
  }

  button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
      Game state = ((Game) getApplicationContext());
      state.incrementScore();
      message = (TextView) findViewById(R.id.message);
      message.setText(state.getScore());
    }
  });
}

This is by far the easiest way to store state of your application which isn’t re-run everytime during screen rotation (orientation changes) or loading different views.

Comments