SharedPreferences Clear/Save

Tirolel picture Tirolel · Mar 18, 2013 · Viewed 56.3k times · Source

Iam trying to make a checker and I want to save a value into SharedPreferences. But i'am not sure if it works

This what I do to save the value is : *

    SharedPreferences prefs = getSharedPreferences("PREFERENCE", MODE_PRIVATE);
    boolean firstrun = prefs.getBoolean("firstrun", true);

    db = openOrCreateDatabase("value.db", Context.MODE_PRIVATE, null); // optional CursorFactory

    if (firstrun) {
          SharedPreferences.Editor editor = prefs.edit();

          db.execSQL("CREATE TABLE startValue (ID Integer Primary Key, myValue Integer)");

          db.execSQL("INSERT INTO startValue (myValue) VALUES (2)"); 

          editor.putBoolean("firstrun", false);
          editor.apply();

           }

    // Save the state
    getSharedPreferences("PREFERENCE", MODE_PRIVATE)
        .edit()
        .putBoolean("firstrun", false)
        .commit();

And to Clear the preferenece from another activity is :

     try{
            db = openOrCreateDatabase("value.db", Context.MODE_PRIVATE, null); // optional CursorFactory

            db.execSQL("DROP TABLE IF EXISTS startValue");
            db.close();

            SharedPreferences preferences = getPreferences(0);
            SharedPreferences.Editor editor = preferences.edit();

            editor.remove("firstrun");
            editor.clear();
            editor.commit();

            this.finish();
        }    
        catch(SQLException ex)
        {
        //catch error here
        }

Issue

But when i'am testing as I see its not clearing the preferences. Am I doing something wrong or?

Answer

AwadKab picture AwadKab · Mar 18, 2013

To clear SharedPreferences use this

SharedPreferences preferences = getSharedPreferences("PREFERENCE", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.clear(); 
editor.commit();

Hope this helped you.