我正在上课。
我是android的新手,我在一个类中声明了全局变量。我在多个活动中使用这些变量,但这些全局变量变为空,而运行时可能仅适用于低内存设备和我用于测试的版本2.3.6
我该如何解决这个问题?
答案 0 :(得分:1)
尝试这样:
创建共享数据类:
<强> SharedData.java 强>
public class SharedData {
private static SharedData instance = new SharedData();
// Getter-Setters
public static SharedData getInstance() {
return instance;
}
public static void setInstance(SharedData instance) {
SharedData.instance = instance;
}
private int notification_index;
private SharedData() {
}
public int getNotification_index() {
return notification_index;
}
public void setNotification_index(int notification_index) {
this.notification_index = notification_index;
}
}
在要设置/获取数据的类中声明/初始化类的实例:
SharedData sharedData = SharedData.getInstance();
设置数据:
sharedData.setNotification_index(123);
获取数据:
int n = sharedData.getNotification_index();
答案 1 :(得分:0)
它的解决方案很少:
此外,您可以保存在SD卡或内存中。
告诉我们您是如何尝试存储价值的,以及重置价值的重要性。
第一个选项的示例代码:
public class GlobalValue extends Application {
private int value = 0;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = gameScore;
}
public void incrementValue(){
value++;
}
}
在Manifest文件中声明此类:
1: <?xml version="1.0" encoding="utf-8"?>
2: <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3: package="com.example"
4: android:versionCode="1"
5: android:versionName="1.0" >
6:
7: <uses-sdk android:minSdkVersion="14" />
8:
9: <application
10: android:icon="@drawable/ic_launcher"
11: android:label="@string/app_name"
12: android:name="GlobalState" >
13:
14: <!-- component definitions -->
15: </application>
16:
17: </manifest>
答案 2 :(得分:0)
我认为您每次都在创建所有活动时创建该类的实例。 在该类
中将所有变量声明为“public static final”如果你想使用那个全局变量而不是在你的活动中使用这样的代码。
SQRUtils.downloader = // change which you want//
SQRUtils.mGson = //if you want to change mgson value//
并且您可以在所有类中每次获取所有数据。在停止该应用程序后,此变量将被删除。