Boldbayar
Boldbayar

Reputation: 875

App crashes when using SharedPreferences

Hello i tried shared preferences but no hope app is crashing . is there any other way to store highscore as simple way?

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();

Below is the logcat output:

    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)

Upvotes: 0

Views: 1189

Answers (2)

You've got extra space in " 1", replace this line

int score1 = Integer.parseInt(textData.toString());

with this

int score1 = Integer.parseInt(textData.toString().trim());

Upvotes: 1

IAmGroot
IAmGroot

Reputation: 13855

Your code makes the assumption that score1 is not blank, and is a valid Integer. You could maybe Add a check for those 2.

You have invalid int " 1"

Because of the extra space. use .trim() to fix this. And also check for blanks for extra safe checking.

  if (textData != null && !textData.toString().trim().equals("")) {
               int score1 = Integer.parseInt(textData.toString().trim());

Upvotes: 2

Related Questions