Sunday, January 27, 2013

Global variables in android

Global variables are variables that can be accessed from more than one activity.
If you only need primitive values than you can pass them in the Intent, but if you have more complex data types this is not an option.
The first thing you might try is to declare the members as static.
This is a VERY BAD idea.
Android can set static instances to null without you knowing and you will spend hours debugging the application.

The correct way to do this is by extending the Application class.
As stated in the Android documentation:
Base class for those who need to maintain global application state.

Bellow is an example of how to use the application class:
package gulyan.gametoolkit.app;

import android.app.Application;

public class GameApplication extends Application {

 private static GameApplication instance = null;

 @Override
 public void onCreate() {
  super.onCreate();
  instance = this;
 }

 public static GameApplication getInstance() {
  return instance;
 }

}
Next, you must edit the AndroidManifest file in order to use the custom application class, by setting the name attribute.
<application
     android:name="gulyan.gametoolkit.app.GameApplication"
     android:icon="@drawable/ic_launcher"
     android:label="@string/app_name"
     android:allowBackup="true"
     android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" >
You can now declare all the variables as members of this class (non-static members).
If you need to access them you can use the getInstance method in order to obtain the application instance. This instance is the same in all the activities.
GameApplication inst = GameApplication.getInstance();
MyVar x = inst.getMyVar();
inst.setMyVar(x);
Hope you find this useful.

2 comments:

  1. check this link
    http://articlesforprogramming.blogspot.in/2013/06/how-to-declare-global-variable-in.html

    ReplyDelete