我試圖以編程方式清除我的應用程序數據。但是我用下面的代碼得到了一個NullPointerEXception
。getCacheDir()的NullPointerException android
這裏是我的代碼: -
public class MyApplication extends Application {
private static MyApplication instance;
@Override
public void onCreate() {
super.onCreate();
instance = this;
}
public static MyApplication 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/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();
}
}
我得到一個NullPointerException
而我嘗試做: -
File cache = getCacheDir();
我怎樣才能解決這個問題?
你如何調用'clearApplicationData()'以及對象是如何實例化的?另請發佈堆棧跟蹤。 – laalto
檢查這個http://stackoverflow.com/questions/4957094/where-is-the-file-when-use-getcachedir –
我想你是錯誤的拋出異常。請再檢查一次。也許調試代碼並遍歷每一行。我認爲這種方式的原因是,這條線在這裏會引起任何問題是沒有意義的。 –