user3034944
user3034944

Reputation: 1761

Clear app data programmatically in Android

I want to apply a logout functionality in my application. Here I want to clear all the user data from the database and sharedPreferences. If I do it manually ie: (Settings-> Applications->app name-> Clear data) I get what I want.

I tried the following code to clear the data programatically, but it does not clear the complete data and the previous user details still prevail.

Here is my code:

public class ClearData extends Application 
{
    private static ClearData instance;
    @Override
    public void onCreate()
    {
        super.onCreate();

        instance = this;
    }

    public static ClearData getInstance() 
    {
        if(instance == null)
            instance = new ClearData();
        return instance;
    }

    public void clearApplicationData(Context mContext)
    {
        File cache = mContext.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));

                    Log.i("TAG", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
                }
            }
        }
    }

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

I call clear the data as:

editor.commit();
ClearData.getInstance().clearApplicationData(_context);

I want to have the behaviour same as the manual process. Any other approach I can follow?

Upvotes: 0

Views: 762

Answers (1)

M D
M D

Reputation: 47817

Try this way: This'll delete your all folder.You just need to pass your Folder Path..

        File file = new File(Your_folder_path);

        if (file.exists()) {
            String deleteCmd = "rm -r " + path;
            Runtime runtime = Runtime.getRuntime();
            try {
                runtime.exec(deleteCmd);
            } catch (Exception e) { 
                e.printStackTrace();
            }
        }

Upvotes: 1

Related Questions