【发布时间】:2016-07-28 11:02:24
【问题描述】:
我不知道我必须在哪里设置这个变量的初始值:
mySharedPreferences.putStringValue("hello", "400");
如果每次打开应用程序都更改它,它不会被重置。
谢谢!!
【问题讨论】:
标签: android string sharedpreferences
我不知道我必须在哪里设置这个变量的初始值:
mySharedPreferences.putStringValue("hello", "400");
如果每次打开应用程序都更改它,它不会被重置。
谢谢!!
【问题讨论】:
标签: android string sharedpreferences
最好的方法是在 get 方法上“设置”默认值,而不是在应用程序第一次启动时设置它。
mySharedPreferences.getString("hello", "400");
通过这种方式,android 会检查是否设置了值。如果没有,它将回退到默认的“400”。
【讨论】:
在应用标签中
<application
android:name=".YourApplication"
android:allowBackup="true"
android:hardwareAccelerated="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
在应用程序的 onCreate 方法中。这是最好的地方。它将在您的应用创建时执行。
public class YourApplication extends Application {
public static Boolean sAppOpened = false;
@Override
public void onCreate() {
super.onCreate();
//Write your code here
sAppOpened = true;
....
}
...
}
【讨论】:
像这样在类范围内声明您的 SHARED PREFERENCE 文件名 -
public static final String SHARED_PREFERENCES = "SHARED_PREF";
您可以在 OnCreate 方法中使用它。
SharedPreferences sharedpreferences = getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
editor.putString("key", "value");
editor.commit();
【讨论】: