【问题标题】:Shared preferences true by default for some reason出于某种原因,共享首选项默认为 true
【发布时间】:2020-04-15 00:13:46
【问题描述】:

如果没有与当前口袋妖怪名称相同的键,我希望我的按钮在最开始显示“catch”,如果有一个并且其值为 true,则显示“release”。默认情况下,我使用 getBoolean 发送“false”。但出于某种原因,我看到每个新口袋妖怪的第一个文字是“释放”。有什么问题?

编辑:我在布局中包含了整个 onCreate 方法和按钮的 onClick 方法。

<Button
    android:id="@+id/button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Catch"
    android:onClick="toggleCatch"
    android:visibility="visible" />

SharedPreferences catchStorage;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_pokemon);

    requestQueue = Volley.newRequestQueue(getApplicationContext());
    url = getIntent().getStringExtra("url");
    nameTextView = findViewById(R.id.pokemon_name);
    numberTextView = findViewById(R.id.pokemon_number);
    type1TextView = findViewById(R.id.pokemon_type1);
    type2TextView = findViewById(R.id.pokemon_type2);
    pokemonName = getIntent().getStringExtra("name");
    catchStorage = getSharedPreferences("catchStorage", Context.MODE_PRIVATE);

    Button catchBut = (Button)findViewById(R.id.button);
    if(catchStorage.getBoolean(pokemonName, false)){
        catchBut.setText("Release");
    }
    else {
        catchBut.setText("Catch");
    }

    load();
}

public void toggleCatch(View view) {
    Button catched = (Button)view;
    SharedPreferences.Editor editor = catchStorage.edit();
    if(catchStorage.getBoolean(pokemonName, false)){
        editor.putBoolean(pokemonName, false);
        editor.commit();
        catched.setText("Catch");
    }
    else {
        editor.putBoolean(pokemonName, true);
        editor.commit();
        catched.setText("Release");
    }
}

【问题讨论】:

  • 能否先卸载应用确保sharedPreference为空?
  • 我试了一下,发现还有一个问题。当一切都干净并且我还没有点击任何按钮时,它会显示我想要的东西。但是当我点击一个按钮时,每个口袋妖怪的按钮现在都显示“释放”,即使我没有更改它们或为它们使用“putBoolean”。
  • 这对我来说听起来像是一个新问题。它与您如何开始单个活动以及如何制作列表有关

标签: java android sharedpreferences


【解决方案1】:

如果变量从未被用户访问或从未创建,如果您或用户更改了此变量,系统将设置 默认值(在这种情况下为 false)共享首选项的值值,默认值被忽略。 见http://developer.android.com/guide/topics/data/data-storage.html#pref

所以要么之前访问过该值,要么设置了某个值。

更完整的代码 sn -p 可能有助于找到原因。

【讨论】:

  • 感谢您的回答。我了解默认值的逻辑,但仍然看不出有什么问题。看起来我做的一切都是正确的。但这是一台机器,对吧?它只是执行命令。所以肯定有什么错误。
猜你喜欢
  • 2013-07-19
  • 2013-06-19
  • 2019-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多