Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 views
in Technique[技术] by (71.8m points)

android - SharedPreferences Clear/Save

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...