Reputation: 1761
I have a app with SharedPreferences. I would like to clear the complete apps data on a button click so that the application starts fresh as it would when it is installed first.
I have tried:
ClearData.java
public class ClearData extends Application
{
private static ClearData instance;
@Override
public void onCreate() {
super.onCreate();
instance = this;
}
public static ClearData getInstance() {
return instance;
}
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));
Log.i("TAG", "**************** File /data/data/mypackage/" + 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();
}
}
Main.java
btnLogout.setOnclickListener(new View.OnClickListner(
{
@Override
public void onClick(View v)
{
ClearData.getInstance().clearApplicationData(); // Gettin error
}
});
But I get a NullPointerException on the above line
Upvotes: 1
Views: 7740
Reputation: 3285
Here is another way to clear the App data completely:
private void clearAppData() {
try {
Runtime runtime = Runtime.getRuntime();
runtime.exec("pm clear " + getApplicationContext().getPackageName() + " HERE");
} catch (Exception e) {
e.printStackTrace();
}
}
Upvotes: 3
Reputation: 31
Don't use a class which extends application, declare
clearApplicationData(Context mContext)
instead of
clearApplicationData()
and
File cache = mContext.getCacheDir();
instead of
File cache = getCacheDir();
in main activity itself. Then call
clearApplicationData(getBaseContext());
on click of button btnLogout. Hope this helps.
Upvotes: 3