![](/img/trans.png)
[英]Android app stores high score value as int in sharedpreferences. The app throws an outofbounds exception if a score over 100 is reached
[英]SharedPreferences. Android, Java
抱歉,我有一个新问题,但是我认为这是可以的,因为我是Android开发的新手(正在开发中)。 我正在学习如何保存我的首选项。 我有一个简单的应用程序:
package com.foxysoft.prefssimple;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
final static String LOG_TAG = "myLogs";
TextView tvInfo;
SharedPreferences sp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvInfo = (TextView) findViewById(R.id.tvInfo);
sp = PreferenceManager.getDefaultSharedPreferences(this);
}
@Override
protected void onResume() {
Log.d(LOG_TAG, "onResume");
Boolean notif = sp.getBoolean("notif", false);
String address = sp.getString("address", "");
String text = "Notifications are " + ((notif) ? "enabled, address = " + address : "disabled");
tvInfo.setText(text);
super.onResume();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem mi = menu.add(0, 1, 0, "Prefs");
mi.setIntent(new Intent(this, PrefActivity.class));
return super.onCreateOptionsMenu(menu);
}
}
如您所见,我有一个小菜单,我的首选项(PrefActivity.class)有一个活动,我的首选项活动有prefs.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="notif"
android:summary="Enable notifications"
android:title="Notifications">
</CheckBoxPreference>
<EditTextPreference
android:key="address"
android:summary="Address for notifications"
android:title="Address">
</EditTextPreference>
</PreferenceScreen>
所以,我的问题是。 我的onResume中有两行:
Boolean notif = sp.getBoolean("notif", false);
String address = sp.getString("address", "");
如果我理解正确,那么每次调用onResume时,都应该将我的“ notif”复选框设置为false,并将“ address”字符串“”(空)设置为..或?..如果没有-为什么? 这两行肯定是在说“请勿假,地址为空”,对吗?
不,您说的不对-您正在读取 存储的偏好设置。
当没有首选项名为“ notif”时; 然后使用您提供给该方法调用的默认值 ; 和false将返回。 但是,如果存在已保存的首选项“ notif”,则将返回为其保存的值 。
只需阅读该方法的相应javadoc即可 ; 它说:
defValue布尔值:如果此首选项不存在,则返回的值。
返回首选项值(如果存在)或defValue。
换句话说:如果您之前存储的是true
,那么将返回该值。
此外,这里的真正答案是:您无需假设 Android API调用的工作方式-所有这些都得到了很好的记录。 因此,如果有疑问,请转到Javadoc。 (当然-虽然我们试图回答问题时要真正准确的-你仍然可以在这里得到一个错误的答案, 真正唯一重要的是API文档说什么!)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.