以编程方式清除Android应用程序数据

时间:2014-05-06 11:08:33

标签: java android logout

我有一个使用SharedPreferences的应用。我希望在按钮单击时清除完整的应用程序数据,以便应用程序在首次安装时启动。

我试过了:

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

但是我在上面的行

上得到了NullPointerException

2 个答案:

答案 0 :(得分:1)

不要使用扩展应用程序的类,声明

clearApplicationData(Context mContext)

而不是

clearApplicationData()

File cache = mContext.getCacheDir();  

而不是

File cache = getCacheDir(); 

在主要活动中。然后拨打

clearApplicationData(getBaseContext());  

点击按钮btnLogout。希望这会有所帮助。

答案 1 :(得分:0)

这是另一种完全清除应用数据的方法:

private void clearAppData() {
        try {
            Runtime runtime = Runtime.getRuntime();
            runtime.exec("pm clear " + getApplicationContext().getPackageName() + " HERE");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }