简体   繁体   中英

Android sharedpreferences

I've been following this tutorial and i am stuck.

public class Main extends Activity {

    SharedPreferences mPrefs;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        firstRunPreferences();

        if(getFirstRun())
        {
            Toast.makeText(Main.this, "firstrun", Toast.LENGTH_SHORT).show();
            setRunned();  
        }
        else
        {           
            Toast.makeText(Main.this, "not firstrun", Toast.LENGTH_SHORT).show();
        }

    }

    public boolean getFirstRun() {
        return mPrefs.getBoolean("firstRun", true);
     }
    public void setRunned() {  
        SharedPreferences.Editor edit = mPrefs.edit();
        edit.putBoolean("firstRun", false);
        edit.commit();
     }
    public void firstRunPreferences() {
        Context mContext = Main.this.getApplicationContext();
        mPrefs = mContext.getSharedPreferences("myAppPrefs", 0); 
     }

}`

Everytime i run it in Eclipse it says "not firstrun". I guess the preferences reset every time the app is reinstalled, so what is wrong with the code? As far as i remember, i saw once "firstrun".

Thanks

I am assuming you are using the Emulator to run your app. Are you closing the emulator between runs?

Check if you have the "Wipe User Data" checkbox ticked in the Target tab of your Debug run configuration in Eclipse.

SharedPreferences are not cleaned by uninstall.

If you want something cleaned after reinstall, put a field in your database.

Stéphane

I'm not sure but I think SharedPreferences are removed when uninstalling, but not when updating an app.

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