2014-06-23 53 views
1

我試圖以編程方式清除我的應用程序數據。但是我用下面的代碼得到了一個NullPointerEXceptiongetCacheDir()的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(); 

我怎樣才能解決這個問題?

+0

你如何調用'clearApplicationData()'以及對象是如何實例化的?另請發佈堆棧跟蹤。 – laalto

+0

檢查這個http://stackoverflow.com/questions/4957094/where-is-the-file-when-use-getcachedir –

+0

我想你是錯誤的拋出異常。請再檢查一次。也許調試代碼並遍歷每一行。我認爲這種方式的原因是,這條線在這裏會引起任何問題是沒有意義的。 –

回答

2

使用

File cache = mContext.getCacheDir(); 

即改寫clearApplicationData功能,因爲getCacheDir()功能需求方面

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 *******************"); 
      } 
     } 
    } 
} 
+0

getCacheDir應該在他的情況下工作正常,因爲應用程序擴展上下文,並且它會得到相同的上下文:http://developer.android.com/reference/android/ app/Application.html。實際上,使用任何Context類都可以完全安全。 –

+0

@androiddeveloper感謝通知,編輯我的答案與第二個選項。 –

3

試試下面的代碼傳遞活動的背景下: -

File cache = getApplicationContext().getCacheDir(); 

這個錯誤發生的原因getCacheDir()功能需要應用的上下文上。

+0

getCacheDir在他的情況下應該可以正常工作,因爲應用程序擴展了上下文,並且您將獲得相同的上下文:developer.android.com/reference/android/app/Application.html。實際上,使用任何Context類完成安全性,而不僅僅是應用程序上下文 –

0

我認爲這個錯誤是因爲你沒有讓這個類成爲真正的應用類來使用。

檢查清單,即「應用程序」標籤的「android:name」屬性設置正確以引用此類。

爲了檢查它是否已初始化,請在「onCreate()」方法中寫入日誌。另外,您應該首先使用「MyApplication getInstance()」或者使用「((MyApplication)getApplicationContext())」調用「clearApplicationData()」。

此外,請注意,應用程序上下文的此「設計模式」適用於99%的情況。唯一不起作用的情況是,當你有內容提供者時,因爲在這種情況下應用程序類不會被初始化。

如果這不是錯誤的原因,請嘗試調試代碼,看看它是否真的到了這一行,並在那裏崩潰。

相關問題