[英]Shared Preference not changing value immediately?
我有一個GridView
並且每個項目是一組打開一個活動,但首先它會檢查,如果這個項目是通過使用解鎖或不boolean
,它的值由保存SharedPreference
,如果它鎖定它改變一個String
名為name
的項目命名並打開AlertDialog
,如果用戶按下肯定按鈕,則應將boolean
值更改為false,這意味着它不再被鎖定並且應該正常打開,但問題是不會改變,用戶必須對其進行解鎖兩次更改它,我使用Log
檢查是否一切正常,除了布爾值未更改之外,其他一切都正常,有人可以告訴我如何解決此問題。
這是我的代碼:
這是我的onCreate
方法:
String name;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main_menu);
final SharedPreferences shared = getSharedPreferences("PrefName", Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = shared.edit();
final int Coins = shared.getInt("CoinsValue", 1000);
final boolean game = (shared.getBoolean("game", true));
// 1. Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(MainMenu.this);
// 2. Chain together various setter methods to set the dialog characteristics
builder.setMessage("Unlock a new set to have more fun")
.setTitle("UNLOCK SET");
// Add the buttons
builder.setPositiveButton("100 coins", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (Coins >= 100){
editor.putInt(name, false).apply();
Toast.makeText(MainMenu.this, "Set Unlocked", Toast.LENGTH_SHORT).show();
coinsValue = Coins - 100;
editor.putInt("CoinsValue", coinsValue);
editor.apply();
Log.e("Msg", "" + name + " value = " + deathparade);
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// 3. Get the AlertDialog from create()
final AlertDialog dialog = builder.create();
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position){
case 9:
Log.e("Msg", "Game value = " + game);
if(game){
name = "game";
editor.putString("nameLock", "game");
editor.apply();
Log.e("Msg", "" + name);
dialog.show();
} else {
editor.putInt("ArrayValue", R.array.game);
editor.putInt("DrawableValue", R.drawable.game_bg);
editor.apply();
startActivity(new Intent(MainMenu.this, MainActivity.class));
}
break;
使用apply()
不會立即保存它。 如果需要立即保存,則應使用commit
但是使用commit可能會阻塞ui線程。
注意:
如果您使用commit
則會收到此警告,告訴您區別
Consider using apply() instead; commit writes its data to persistent storage immediately, whereas apply will handle it in the background
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.