共享preferences清除/保存preferences

2023-09-04 23:12:20 作者:给糖就不闹

大家好

荫试图让一个检查,我想保存的值到共享preferences。但IAM不知道它的工作原理

Iam trying to make a checker and I want to save a value into sharedpreferences. But iam not sure if it works

这是我做的,保存的值是:*

       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();

,并从另一个活动清除preferenece是:

  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)
        {

        }

问题

但是,当我看到它不清除prefences,荫做某事错误或IAM测试?

But when iam testing as I see its not clearing the prefences, Iam doing sth wrong or?

推荐答案

要清除共享preferences使用

To clear SharedPreferences use this

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

希望这有助于你。

Hope this helped you.

 
精彩推荐