简体   繁体   中英

value storing in Shared Preferences

hi I want to save my high score value through shared preferences. but when I go to another activity and then get into same activity my high score value again begins with zero. I know its simple but I don't know what mistake I am doing. here is the example code.

    private static final String FORMAT = "%02d:%02d:%02d";
    int count = 0, high;
    int seconds , minutes;
    SharedPreferences sharedPreferences;
    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);

        sharedPreferences = getPreferences(MODE_PRIVATE);
        int savedPref = sharedPreferences.getInt("HighScore", 0);

        final TextView counter=(TextView)findViewById(R.id.taptimes);
        final TextView countdown=(TextView)findViewById(R.id.countdown);
        final TextView highScore = (TextView)findViewById(R.id.highScore);
        final Button b1=(Button)findViewById(R.id.keypress);

        b1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                countClick();
            }

            private void countClick() {
                // TODO Auto-generated method stub
                count++;
                counter.setText(String.valueOf(count));
                if (count > high){

                    highScore.setText(Integer.toString(count));
                    high = count;

                    sharedPreferences = getPreferences(MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putInt("HighScore", high);
                    editor.commit();
                }
            }
        });


        new CountDownTimer(10000, 1000) {//CountDownTimer(edittext1.getText()+edittext2.getText()) also parse it to long

             public void onTick(long millisUntilFinished) {
                 countdown.setText("Time remaining: " + millisUntilFinished / 1000);
              //here you can have your logic to set text to edittext
             }

             public void onFinish() {
                 countdown.setText("Time Over!");
                 b1.setEnabled(false);
             }
            }
            .start();

    }

    @Override
    public void onBackPressed()
    {
        super.onBackPressed();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.home, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

    }


}

The only problem I see, is that you're not doing anything with savedPref :

int savedPref = sharedPreferences.getInt("HighScore", 0);

I think it should be:

high  = sharedPreferences.getInt("HighScore", 0);

Doesn't your IDE trigger a warning that savedPref is useless?

I would suggest you to make a different class for shared preferences. I have been using this way for long time now and it is very easy maintenance for shared preferences. Here is my shared preference code

    public class AppSharedPreferences {

            private SharedPreferences appSharedPrefs;
            private SharedPreferences.Editor prefsEditor;
            private static AppSharedPreferences appSharedPrefrence;

            public AppSharedPreferences(Context context) {
            this.appSharedPrefs = context.getSharedPreferences("sharedpref", Context.MODE_PRIVATE);
            this.prefsEditor = appSharedPrefs.edit();
        }

        public AppSharedPreferences() {

        }

        public static AppSharedPreferences getsharedprefInstance(Context con) {
            if (appSharedPrefrence == null)
                appSharedPrefrence = new AppSharedPreferences(con);
            return appSharedPrefrence;
        }

        public SharedPreferences getAppSharedPrefs() {
            return appSharedPrefs;
        }

        public void setAppSharedPrefs(SharedPreferences appSharedPrefs) {
            this.appSharedPrefs = appSharedPrefs;
        }

        public SharedPreferences.Editor getPrefsEditor() {
            return prefsEditor;
        }

        public void Commit() {
            prefsEditor.commit();
        }

        public void clearallSharedPrefernce() {
            prefsEditor.clear();
            prefsEditor.commit();
        }
    public void setHelperId(int helperId)
    {
        this.prefsEditor=appSharedPrefs.edit();
        prefsEditor.putInt("helper_id", helperId);
        prefsEditor.commit();
    }
        public int getHelperId()
        {
            return appSharedPrefs.getInt("helper_id",0);
        }
}

for saving values in shared preference create get and set method as shown at end of code. Let all other methods of the code as it is.

And to use this code in your class just create an instance of shared preference in your class like this

appSharedPreferences= AppSharedPreferences.getsharedprefInstance(YourActivity.this) ;

i think the way you are retrieving and changing shared preferences might be the issue. Try fetching an instance of shared preferences as follows

 sharedPreferences=context.getSharedPreferences(Constants.MYUSERPREF, 0); //the 0 in the initialization is for private mode.

Also, an important thing to do is after you change the values and call editor.commit(); also call editor.apply(); to save the changes to sharedPreferences

Please create common class for your Application Follow bellow Steps :

Step 1:

Create Application level Class

public class AppConfig extends Application {

private static AppConfig appInstance;
private static SharedPreferences sharedPreferences;
private static SharedPreferences.Editor sharedPreferencesEditor;
private static Context mContext;

@Override
public void onCreate()
{
    super.onCreate();
    appInstance = this;
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    sharedPreferencesEditor = sharedPreferences.edit();
    setContext(getApplicationContext());

}

public static Context getContext() {
    return mContext;
}

public static void setContext(Context mctx) {
    mContext = mctx;
}


public static AppConfig getAppInstance() {
    if (appInstance == null)
        throw new IllegalStateException("The application is not created yet!");
    return appInstance;
}

/**
 * Application level preference work.
 */
public static void preferencePutInteger(String key, int value) {
    sharedPreferencesEditor.putInt(key, value);
    sharedPreferencesEditor.commit();
}

public static int preferenceGetInteger(String key, int defaultValue) {
    return sharedPreferences.getInt(key, defaultValue);
}

public static void preferencePutBoolean(String key, boolean value) {
    sharedPreferencesEditor.putBoolean(key, value);
    sharedPreferencesEditor.commit();
}

public static boolean preferenceGetBoolean(String key, boolean defaultValue) {
    return sharedPreferences.getBoolean(key, defaultValue);
}

public static void preferencePutString(String key, String value) {
    sharedPreferencesEditor.putString(key, value);
    sharedPreferencesEditor.commit();
}

public static String preferenceGetString(String key, String defaultValue) {
    return sharedPreferences.getString(key, defaultValue);
}

public static void preferencePutLong(String key, long value) {
    sharedPreferencesEditor.putLong(key, value);
    sharedPreferencesEditor.commit();
}

public static long preferenceGetLong(String key, long defaultValue) {
    return sharedPreferences.getLong(key, defaultValue);
}

public static void preferenceRemoveKey(String key) {
    sharedPreferencesEditor.remove(key);
    sharedPreferencesEditor.commit();
}

public static void clearPreference() {
    sharedPreferencesEditor.clear();
    sharedPreferencesEditor.commit();
}

}

Step 2:

Define this class into Manifest.xml in Application tag like this

<application
    android:name=".AppConfig">
 </application>

Step 3:

You can use below code into your activity

AppConfig.preferencePutInteger("HighScore",yourScore);
AppConfig.preferenceGetInteger("HighScore", 0)

In the OnCreate method I just missed these.. thanks for everyone

high = sharedPreferences.getInt("HighScore", 0);
 highScore.setText(Integer.toString(high));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM