首页 > 解决方案 > Android - 切换应用程序后我的全局变量值返回 null

问题描述

我正在使用 GlobalVariable 文件在整个应用程序期间保存数据,但是如果我切换到另一个应用程序并返回,它会返回空值。

下面是我的代码:

在清单中:

 <application
    ..
    android:name=".MyApplication" >

对于全局变量类:

public class MyApplication extends Application {
public int rowId = 0;
}

活动内

int mRowId = ((MyApplication) getApplicationContext()).rowId;

标签: androidglobal-variables

解决方案


您需要制作它staticfinal但仅将其与 getter 和 setter 一起使用。

类似于以下内容

 public class MyApplication extends Application {


 public final static int rowId = 0;

请不要忘记您的初始化和设置器和获取器:

 int rowId;

public int getRowId() {
    return rowId;
}

public void setRowId(int rowId) {
    this.rowId = rowId;
}

从类外部设置值,例如:

  MyApplication.rowId =  //whatever returns int

从类外部/内部获取值,例如:

  int TempInt = MyApplication.rowId; // TempInt will have the value of rowId

检查什么是 setter 和 getter: https ://dzone.com/articles/why-should-i-write-getters-and-setters


推荐阅读