'How to clear entire app data without force closing the app in android

I want to clear the entire app data like

Settings->Applications-> ManageApplications-> My_application->Clear Data.

I tried this code but it is force closing the app.

try {
  // clearing app data
  String packageName = getActivity().getPackageName();
  Runtime runtime = Runtime.getRuntime();
  runtime.exec("pm clear " + packageName);
} catch (Exception e) {
  e.printStackTrace();
}

Please help me to solve the issue, Thank you.



Solution 1:[1]

Try this way to clear cache and Application data (Tried and Worked perfectly on Lollipop):-

(1) Add below ClearApplicationData class with change your AcivityName in progressDialog and your sharedPreference name to clear with editor:-

private class ClearApplicationData(Context mContext) extends AsyncTask<Void, String, String> {

    ProgressDialog mDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mDialog = new ProgressDialog(MainActivity.this); //Change MainActivity as per your activity
        mDialog.setMessage("Data is clearing...");
        mDialog.setCancelable(false);
        mDialog.show();
    }

    protected String doInBackground(Void... urls) {
        SharedPreferences.Editor editor = mContext.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE).edit();
        editor.clear();
        editor.apply();
        File cacheDir = mContext.getCacheDir();
        File appDir = new File(cacheDir.getParent());
        deleteRecursive(appDir);
        return "";
    }

    protected void onPostExecute(String result) {
        mDialog.dismiss();
        Toast.makeText(mContext, "Data is cleared.", Toast.LENGTH_SHORT).show();
        finish();  //Activity finish
    }
}

(2) add below function to delete files in recursive method:-

public void deleteRecursive(File fileOrDirectory) {

    if (fileOrDirectory.isDirectory()) {
        for (File child : fileOrDirectory.listFiles()) {
            deleteRecursive(child);
        }
    }
    fileOrDirectory.delete();
}

(3) call the class when you want to clear application data:-

new ClearApplicationData(context).execute();

Solution 2:[2]

here is a way to do it in Kotlin :

fun clearData() {
    val cache = getCacheDir()
    val appDir = File(cache.getParent())
    if (appDir.exists()) {
        val children = appDir.list();
        for (s in children) {
            if (!s.equals("lib")) {
                deleteDir(File(appDir, s))
                Log.i("TAG", "File /data/data/APP_PACKAGE/" + s + " DELETED")
            }
        }
    }
}

fun deleteDir( dir : File?) : Boolean {
    if (dir != null && dir.isDirectory()) {
        val children = dir.list()
        for ( i in children) {
            val success = deleteDir( File(dir, i));
            if (!success) {
                return false
            }
        }
    }

    return dir!!.delete()
}

Solution 3:[3]

/**You can clear the data programmatically as well without affecting
   Shared Preferences or data base data**/

 public static void deleteCache(Context context)
{
    try
    {
        File dir = context.getCacheDir();
        deleteDir(dir);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

private static boolean deleteDir(File dir)
{
    if (dir != null && dir.isDirectory())
    {
        String[] children = dir.list();
        for (String aChildren : children)
        {
            boolean success = deleteDir(new File(dir, aChildren));

            if (!success)
            {
                return false;
            }
        }
        return dir.delete();
    }
    else
    return dir != null && dir.isFile() && dir.delete();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Jeremy Vandermeersch
Solution 3 yash786