Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...