删除共享首选项键/值对

The*_*heo 8 android sharedpreferences

我将一些付款值存储在一个活动中

SharedPreferences spreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
productId = spreferences.getString("productId", "");
purchaseToken = spreferences.getString("purchaseToken", "");
orderId = spreferences.getString("orderId", "");
Run Code Online (Sandbox Code Playgroud)

现在我在另一个中检索它们

SharedPreferences spreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
productId = spreferences.getString("productId", "");
purchaseToken = spreferences.getString("purchaseToken", "");
orderId = spreferences.getString("orderId", "");
Run Code Online (Sandbox Code Playgroud)

我的问题是在检索它们后在第二个Activity中删除它们.谢谢.

Pan*_*mar 20

SharedPreferences.Editor remove (String key)做同样的.

它在编辑器中标记应该删除首选项值,一旦调用commit(),将在实际首选项中完成.

请注意,在提交回首选项时,无论是否在此编辑器上调用put方法之前或之后调用remove,都会先执行所有删除操作.


所以在你的情况下,你可以使用它

SharedPreferences.Editor editor = spreferences.edit();
editor.remove("productId");
editor.remove("purchaseToken");
editor.remove("orderId");
editor.commit();
Run Code Online (Sandbox Code Playgroud)

  • 使用 apply() 比使用 commit() 更好。 (3认同)

Dur*_*tel 5

要在SharedPreference中存储值,请使用以下代码:

SharedPreferences spreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Editor spreferencesEditor = spreferences.edit();
spreferencesEditor.putString("productId", "value of prodId");
spreferencesEditor.putString("purchaseToken", "value of purchaseToken");
spreferencesEditor.putString("orderId", "value of orderId");
spreferencesEditor.commit();
Run Code Online (Sandbox Code Playgroud)

要从SharedPreference中删除特定值,请使用以下代码:

SharedPreferences spreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Editor spreferencesEditor = spreferences.edit();
spreferencesEditor.remove("productId"); //we are removing prodId by key
spreferencesEditor.commit();
Run Code Online (Sandbox Code Playgroud)

要从SharedPreference中删除所有值,请使用以下代码:

SharedPreferences spreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Editor spreferencesEditor = spreferences.edit();
spreferencesEditor.clear();
spreferencesEditor.commit();
Run Code Online (Sandbox Code Playgroud)