java - 出于某种原因,共享首选项默认为 true
问题描述
如果没有与当前口袋妖怪名称相同的键,我希望我的按钮在开始时显示“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");
}
}
解决方案
如果变量从未被用户访问或从未创建,则共享首选项的值将由系统设置默认值(在这种情况下为 false),如果您或用户更改了此值,则默认值将被忽略。请参阅http://developer.android.com/guide/topics/data/data-storage.html#pref
因此,要么之前访问过该值,要么设置了某个值。
更完整的代码片段可能有助于找到原因。