我想訪問共享首選項靜態方式,以避免使用過多的代碼,但是當我閱讀共享首選項,看起來像沒有保存靜態方法「setSyncDBIsNeeded()」,我做錯了什麼?爲什麼靜態共享首選項未保存?
所有MyApplication代碼:
public class MyApplication extends Application {
private static MyApplication instance;
@Override
public void onCreate() {
super.onCreate();
instance = this;
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this)
.name(Realm.DEFAULT_REALM_NAME)
.schemaVersion(0)
.deleteRealmIfMigrationNeeded()
.build();
Realm.setDefaultConfiguration(realmConfiguration);
}
public static Context getContext() {
return instance.getApplicationContext();
}
}
我的喜好的活動:
public class PreferenceController {
SharedPreferences sharedPreferences;
private static String project = "com.example.myproject";
public PreferenceController() {
sharedPreferences = MyApplication.getContext().getSharedPreferences(project, Context.MODE_PRIVATE);
}
public PreferenceController(Context context) {
sharedPreferences = context.getSharedPreferences(project, Context.MODE_PRIVATE);
}
/* getters and setters */
// Static methods
public static void setSyncDBIsNeeded(boolean value) {
Log.d("PREFCON","Setted DBSyncNeeded : "+value);
getSharedPrefferences().edit().putBoolean("DBSyncNeeded", value);
}
public static boolean getSyncDBIsNeeded() {
Log.d("PREFCON","DBSyncNeeded: "+getSharedPrefferences().getBoolean("DBSyncNeeded", false));
return getSharedPrefferences().getBoolean("DBSyncNeeded", false);
}
private static SharedPreferences getSharedPrefferences() {
return MyApplication.getContext().getSharedPreferences(project, Context.MODE_PRIVATE);
}
}
然後在另一個類我做的:
PreferenceController.setSyncDBIsNeeded(true);
PreferenceController.getSyncDBIsNeeded();
其印在日誌:
07-14 14:24:04.665 27658-27658/com.example.myproject D/PREFCON: Setted DBSyncNeeded : true
07-14 14:24:04.665 27658-27658/com.example.myproject D/PREFCON: DBSyncNeeded: false
設置該值後,您忘記調用commit()。嘗試'getSharedPrefferences()。edit()。putBoolean(「DBSyncNeeded」,value).commit();' – Rashin
調用「commit()」工作;) – MikeOx