【问题标题】:Clear app data programatically doesnt work以编程方式清除应用数据不起作用
【发布时间】:2016-10-27 14:23:52
【问题描述】:

我有一个“注销”按钮,单击它们后我想清除应用程序的所有数据和缓存。我在这个站点的类似主题中发现了删除数据的方法:

   public void clearApplicationData() {
    File cache = getCacheDir();
    File appDir = new File(cache.getParent());
    if(appDir.exists()){
        String[] children = appDir.list();
        for(String s : children){
            if(!s.equals("lib")){
                deleteDir(new File(appDir, s));
            }
        }
    }
}

public boolean deleteDir(File dir) {
    if (dir != null && dir.isDirectory()) {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }

    return dir.delete();
}

但是当我使用代码时:

logoutButton.setOnClickListener(new View.OnClickListener() {
          @Override
           public void onClick(View v) {
           clearApplicationData();
           finish();
           startActivity(new Intent(ProfileActivity.this, MainActivity.class));
       }
      });

我的应用重新启动,但应用数据并未删除。那么,如何以编程方式删除应用程序的所有缓存和数据?

【问题讨论】:

  • “但应用数据没有删除”——您是如何确定这一点的?
  • 数据库中的数据没有被删除。共享首选项值不会删除...
  • 详细说明,您为确定“数据库中的数据未删除。共享首选项值未删除”而采取的每一步。例如,您是否将startActivity() 注释掉,然后查看实际文件是否消失了?也许您的新 MainActivity 实例正在显示您已缓存在内存中的一些数据。
  • SharedPreferences.Editor editor = preferences.edit(); editor.putString(V1_KEY, "someValue"); editor.apply();然后 clearApplicationData();结束(); Intent i = new Intent(ProfileActivity.this, MainActivity.class);开始活动(一);然后我得到值preferences.getString(V1_KEY, null);并获得“someValue”而不是 null ...

标签: android appdata app-data


【解决方案1】:

首先,您的代码不一定会删除存储SharedPreferences 的文件。它的位置是无证的,IIRC,它不一定在你要删除的范围内。

其次,SharedPreferences 被缓存在你的进程中。即使您成功删除了文件,缓存的SharedPreferences 也不会知道您删除了它。在您的进程终止之前,您将继续有权访问“已删除”的SharedPreferences 数据。

如果您的目标是能够删除数据,请仅将数据存储在您控制的位置以及您控制数据缓存方式的位置。将您对 SharedPreferences 的使用替换为其他内容(例如,SQLite 数据库或您自己管理的某些文件)。

【讨论】:

    猜你喜欢
    • 2014-06-22
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 2020-06-25
    • 2014-07-21
    • 1970-01-01
    相关资源
    最近更新 更多