android - Android - 切换应用程序后我的全局变量值返回 null
问题描述
我正在使用 GlobalVariable 文件在整个应用程序期间保存数据,但是如果我切换到另一个应用程序并返回,它会返回空值。
下面是我的代码:
在清单中:
<application
..
android:name=".MyApplication" >
对于全局变量类:
public class MyApplication extends Application {
public int rowId = 0;
}
活动内
int mRowId = ((MyApplication) getApplicationContext()).rowId;
解决方案
您需要制作它static
,final
但仅将其与 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
推荐阅读
- javascript - 如何在 vue.js 中访问 setIntervall 函数之外的变量?
- git - 移动到不同的分支,丢失了更改 - 有办法回来吗?
- java - 在 Java 中解析 Content-Type 标头而不验证字符集
- dijkstra - 在 VRP 上实现蚁群优化
- terraform - 当代码移动到模块时,Terraform 正在破坏 AWS 资源
- arrays - 将 JSON 数据推送到 ANGULAR 对象数组中
- google-home - 是否可以为 action.devices.EXECUTE 发送延迟响应
- spring-boot - 我的 Spring Boot 应用程序卡住了一段时间,并在启动过程中一段时间后存在
- python - Correct orientation of an image based on 4 Qpoints
- regex - 当没有输入信息时,如何在 coq 问题中断言 (H4: [] = [] ++ [])?