如何删除应用程序的SharedPreferences数据?
我正在创建一个使用大量web服务来同步数据的应用程序。出于测试目的,我需要在重新启动应用程序时删除一些SharedPreferences值。
如何删除应用程序的SharedPreferences数据?
我正在创建一个使用大量web服务来同步数据的应用程序。出于测试目的,我需要在重新启动应用程序时删除一些SharedPreferences值。
当前回答
要删除特定的值:SharedPreferences.Editor.remove()后面跟着一个commit()
SharedPreferences.Editor.clear()后面跟着一个commit()
如果您不关心返回值,并且从应用程序的主线程中使用它,请考虑使用apply()。
其他回答
根据API 24(牛轧糖),你可以这样做:
context.deleteSharedPreferences("YOUR_PREFS");
然而,没有向后兼容性,所以如果你支持小于24的版本,请坚持使用:
context.getSharedPreferences("YOUR_PREFS", Context.MODE_PRIVATE).edit().clear().apply();
如果不需要每次都删除它,您可以手动从:
>应用程序->管理应用程序->(选择您的应用程序) ->清除数据或卸载
更新版本的Android:
设置—>应用程序—>(选择应用程序)—>存储—>清理数据 和清空缓存
从任意类中集中清除所有SharedPreferences:
public static SharedPreferences.Editor getEditor(Context context) {
return getPreferences(context).edit();
}
然后从任何类:(commit返回一个布尔值,你可以检查你的Preferences是否被清除)
Navigation.getEditor(this).clear().commit();
或者你可以用apply;返回为空
Navigation.getEditor(this).clear().apply();
芬兰湾的科特林:
var prefs2: SharedPreferences? = context!!.getSharedPreferences("loginFB", 0)
prefs2!!.edit().remove("email").commit()
Editor editor = getSharedPreferences("clear_cache", Context.MODE_PRIVATE).edit();
editor.clear();
editor.commit();