Alex D.
Alex D.

Reputation: 1423

Clear app data programatically doesnt work

I have a button "Logout", and after click them i want to clear all data and cache of app. I found in similar topics in this site methods to delete data:

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

But when i use the code:

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

my app restarts, but app data doesnt delete. So, how to delete programatically all cache and data of app?

Upvotes: 0

Views: 137

Answers (1)

CommonsWare
CommonsWare

Reputation: 1007584

First, your code does not necessarily delete the file where SharedPreferences are stored. Its location is undocumented, IIRC, and it does not necessarily have to be in the scope of what you are deleting.

Second, SharedPreferences are cached in your process. Even if you do successfully delete the file, the cached SharedPreferences will not know that you deleted it. Until your process terminates, you will continue to have access to the "deleted" SharedPreferences data.

If your objective is to be able to delete data, only store data in places that you control, and where you control how that data gets cached. Replace your use of SharedPreferences with something else (e.g., SQLite database, or some file that you manage yourself).

Upvotes: 1

Related Questions