gpt4 book ai didi

java - 共享偏好不会立即改变值?

转载 作者:行者123 更新时间:2023-12-02 04:34:47 26 4
gpt4 key购买 nike

我有一个 GridView,每个项目都是一个打开 Activity 的集合,但首先它使用其值为的 boolean 值来检查该项目是否已解锁由 SharedPreference 保存,如果它被锁定,则会将名为 nameString 更改为项目名称,并打开一个 AlertDialog如果用户按下肯定按钮,它应该将 boolean 值更改为 false,这意味着它不再锁定并且应该正常打开,但问题是这不会改变用户必须解锁两次以使其更改,我使用 Log 检查一切是否正常,除了 boolean 值没有改变之外,一切都正常,有人可以告诉如何解决这个问题。

这是我的代码:

这是我的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,您会收到此警告,告诉您差异

考虑使用 apply() 代替; commit 会立即将数据写入持久存储,而 apply 会在后台处理

关于java - 共享偏好不会立即改变值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30982632/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com