Question

In my app am storing the score its an integer by using shared preference.
Its stores the score whenever the score gets higher than previous one. (If the score is lower than the previous one it wont store.) But when I completely close the app (i.e) closed from task manager and again restarted the score is reset by new score even though my current score is lower than previous one.

Here the code:

SharedPreferences pref = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
if (mScr > tempScore) {
    Editor editor = pref.edit();
    editor.putInt("key_name", mScr);
    editor.commit();
}
tempScore = pref.getInt("key_name", 0);

Can any one say how to over come this?

Was it helpful?

Solution 8

tempScore=pref.getInt("key_name",0);
        if(mScr>tempScore)
        {
            Editor editor = pref.edit();
        editor.putInt("key_name", mScr);
        editor.commit();
        //tempScore=pref.getInt("key_name",0);
                }
        tempScore=pref.getInt("key_name",0);

This one workd

OTHER TIPS

try using following code

SharedPreferences pref =getSharedPreferences(PREF_NAME, MODE_PRIVATE);
tempScore = pref.getInt("key_name",0);
if(mScr>tempScore)
        {
            Editor editor = pref.edit();
        editor.putInt("key_name", mScr);
        editor.commit();
           }
        tempScore=pref.getInt("key_name",0);

Explanation : you are holding previous score in tempScore and that is a static variable. Also you are storing the previous high score in shared preferences. So, why not read the current value in shared preferences and compare with the actual value from prefs rather than using the previously modified variable.

In above code i have retrieved the value from prefs and assigned to the tempScore variable. This will ensure that even if you force close the application you will get the correct value stored in prefs for comparison thus fullfilling your condition.

Before your if condition use this line

tempScore = pref.getInt("key_name", 0);

I hope it will work fine

I don't know what's your way to store and retrieve data but I'm pretty sure that this way works perfectly:

to save :

private void savePreferences(int score) {
        SharedPreferences sharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(this);
        Editor editor = sharedPreferences.edit();
        editor.putInt("score", score);
        editor.commit();
    }

to load :

private void loadSavedPreferences() {
        SharedPreferences sharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(this);
        int score = sharedPreferences.getInt("score", 5); // 5 here is the default value when you get nothing 
        score_textview.setText(Integer.toString(score)); // if you want to set it for a TextView for example
    }
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;    
public class SessionManager {
        // Shared Preferences
        SharedPreferences pref;

        // Editor for Shared preferences
        Editor editor;

        // Context
        Context _context;

        // Shared pref mode
        int PRIVATE_MODE = 0;

        // Sharedpref file name
        private static final String PREF_NAME = "Pref";


        // User name (make variable public to access from outside)
        public static final Int KEY_NAME = "mScr";


        // Constructor
        public SessionManager(Context context){
            this._context = context;
            pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
            editor = pref.edit();
        }

        public void ScoreStoring(Int mScr){

            // Storing name in pref
            editor.putInt(KEY_NAME, mScr);

            // commit changes
            editor.commit();
        }   
    }

keep an one class for above code ,whenever you want import above class in another activity like below code

SessionManager session;
SharedPreferences pref =getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
tempScore=pref.getInt(KEY_NAME,0);
if(mScr>tempScore)
        {
            session.ScoreStoring(mScr);
           }

This sessionManager global class keep your values until your application uninstall.

  1. Reason:since tempScore is static. when your restart, tempScore became 0. so mScr>tempScore will became true and store mScr.
  2. Solution: To overcome this. you can customer your own Application and read preference to tempScore in its onCreate method

The issue is that you're relying on a static field to store your integer. You can't do this because the class will be unloaded when the application process is killed. You need to store your integer to shared preferences (or some other form of persistent storage) when your Activity is paused and retrieve it when it is created or resumed.

As you are using tempScore as static, it is causing the issue.

Statics are global to the process. So their value will last for the lifetime of the process, which is usually much longer than an individual activity instance.

But when I completely close the app(i.e)closed from task manager and again restarted the score is reset by new score even though my current score is lower than previous one

When you do that, the Task manager kills the process of your application. Hence, your static variable loses its value.So next time when you start the app again, you get the default value of that static variable.

In your case, you will get value 0 for tempScore, as you are using int. Hence condition in 'if()' will be true in that case.

I think, one of the best practices in coding is to avoid static variables wherever possible. And one way to do that in Android, by using a class extended from Application class.

public class MyApplication extends Application {

     private int tempScore; 

     public int getTempScore() {
        return tempScore;
     }

     public void setTempScore(int tempScore) {
        this.tempScore = tempScore;
     } 
}

Since for an application there will be only one Application object, you can always get and set the custom application object’s variables anywhere from your application as follows.

((MyApplication)getApplication()).setTempScore();
((MyApplication)getApplication()).getTempScore();

The application object’s life time is throughout the application’s life (and so your custom application object’s) and using the get(), set() method you can manage its data members, and hence avoiding a static variable in your application.

Hope it helps you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top