您好我尝试过共享首选项,但没有希望应用程序崩溃。有没有其他方式以高分为单位存储高分?
SharedPreferences prefs = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
TextView outputView = (TextView) findViewById(R.id.textscore);
CharSequence textData = outputView.getText()
if (textData != null) {
int score1 = Integer.parseInt(textData.toString());
if(score1 > prefs.getInt(TEXT_DATA_KEY, 0))
{
editor.putInt(TEXT_DATA_KEY, score1);
editor.commit();
以下是logcat输出:
03-17 19:33:55.214: E/AndroidRuntime(7434): FATAL EXCEPTION: main
03-17 19:33:55.214: E/AndroidRuntime(7434): java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
03-17 19:33:55.214: E/AndroidRuntime(7434): at android.app.SharedPreferencesImpl.getInt(SharedPreferencesImpl.java:221)
03-17 19:33:55.214: E/AndroidRuntime(7434): at com.example.dip.App2Activity$1.onClick(App2Activity.java:117)
03-17 19:33:55.214: E/AndroidRuntime(7434): at android.view.View.performClick(View.java:3530)
03-17 19:33:55.214: E/AndroidRuntime(7434): at android.view.View$PerformClick.run(View.java:14201)
03-17 19:33:55.214: E/AndroidRuntime(7434): at android.os.Handler.handleCallback(Handler.java:605)
03-17 19:33:55.214: E/AndroidRuntime(7434): at android.os.Handler.dispatchMessage(Handler.java:92)
03-17 19:33:55.214: E/AndroidRuntime(7434): at android.os.Looper.loop(Looper.java:137)
03-17 19:33:55.214: E/AndroidRuntime(7434): at android.app.ActivityThread.main(ActivityThread.java:4519)
03-17 19:33:55.214: E/AndroidRuntime(7434): at java.lang.reflect.Method.invokeNative(Native Method)
03-17 19:33:55.214: E/AndroidRuntime(7434): at java.lang.reflect.Method.invoke(Method.java:511)
03-17 19:33:55.214: E/AndroidRuntime(7434): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
03-17 19:33:55.214: E/AndroidRuntime(7434): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
03-17 19:33:55.214: E/AndroidRuntime(7434): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:2)
您的代码假设score1不为空,并且是有效的整数。你可以为那些2添加支票。
你有无效的" 1"
由于额外的空间。使用.trim()
来解决此问题。并检查空白是否有额外的安全检查。
if (textData != null && !textData.toString().trim().equals("")) {
int score1 = Integer.parseInt(textData.toString().trim());
答案 1 :(得分:1)
你在"中有额外的空间。 1",替换此行
int score1 = Integer.parseInt(textData.toString());
用这个
int score1 = Integer.parseInt(textData.toString().trim());