// My Class Global Variables Save File Global.Java
public class Global {
public static int myVi;
public static String myVs;
}
// How to used on many Activity
Global.myVi = 12;
Global.myVs = "my number";
........
........
........
int i;
int s;
i = Global.myVi;
s = Global.myVs + " is " + Global.myVi;
public class Global {
public static int ivar1, ivar2;
public static String svar1, svar2;
public static int[] myarray1 = new int[10];
}
// How to use other or many activity
Global.ivar1 = 10;
int i = Global.ivar1;
public class FavoriteColorsApplication extends Application {
private static FavoriteColorsApplication application;
private FavoriteColorsService service;
public FavoriteColorsApplication getInstance() {
return application;
}
@Override
public void onCreate() {
super.onCreate();
application = this;
application.initialize();
}
private void initialize() {
service = new FavoriteColorsService();
}
public FavoriteColorsService getService() {
return service;
}
}
然后你可以在任何时候从你的自定义Application对象中调用你的单例:
public class FavoriteColorsActivity extends Activity {
private FavoriteColorsService service = null;
private ArrayAdapter<String> adapter;
private List<String> favoriteColors = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorite_colors);
service = ((FavoriteColorsApplication) getApplication()).getService();
favoriteColors = service.findAllColors();
ListView lv = (ListView) findViewById(R.id.favoriteColorsListView);
adapter = new ArrayAdapter<String>(this, R.layout.favorite_colors_list_item,
favoriteColors);
lv.setAdapter(adapter);
}
2)。你可以让你的控制器只创建一个它自己的单例:
public class Controller {
private static final String TAG = "Controller";
private static sController sController;
private Dao mDao;
private Controller() {
mDao = new Dao();
}
public static Controller create() {
if (sController == null) {
sController = new Controller();
}
return sController;
}
}