2011-06-03 88 views
0

在以下代碼:爲什麼應用程序中的getContentResolver()會導致NullPointerException?

public class ApplicationContext extends Application 
{ 

    private static ApplicationContext instance; 

    public ApplicationContext() 
    { 
     instance = this; 
     final String strID = Secure.getString(getContentResolver(), Secure.ANDROID_ID); 
    } 

    public static Context getContext() 
    { 
     return instance; 
    } 
} 

getContentResolver()導致一個NullPointerException。爲什麼?

我覺得這是例外尤其令人困惑,因爲谷歌指出「你從一個活動或其它應用程序組件的實現中調用getContentResolver()得到一個ContentResolver的」

http://developer.android.com/guide/topics/providers/content-providers.html

回答

4

重寫時,執行此oncreate比你的構造函數更好。我猜你的應用還沒有上下文。

其實,這裏是我昨天做了一些LVL代碼:

/** Called when the activity is first created. */ 

@Override 
public void onCreate() { 
    super.onCreate(); 
    LICENSED_APP_ID = Secure.getString(getContentResolver(), Secure.ANDROID_ID); 
}//cons 

它就像一個魅力...

+0

它在Activity.onCreate()中可以正常工作,但是應用程序構造函數看起來很方便,因爲我想每次啓動時只查找一次數據。 – 2011-06-03 22:03:54

+0

'onCreate()'只在每次啓動時發生一次。你永遠不需要在一個Activity的構造函數中放入功能。閱讀[this](http://developer.android.com/guide/topics/fundamentals/activities.html#Lifecycle)。 – 2011-06-03 22:16:51

+0

應用程序必須具有上下文,因爲它擴展了擴展上下文的ContextWrapper。 – 2011-06-05 08:20:15

0

「應用」類不是一個「應用程序組件」。 http://developer.android.com/guide/topics/fundamentals.html#Components

爲了解決這個問題,我的計劃是從服務中獲取ANDROID_ID。

+0

你是什麼意思應用程序類不在應用程序組件中。我不認爲你需要像服務這樣的額外進程來獲得該列表中的ANDROID_ID ... – Snicolas 2011-06-05 11:46:33

+0

,這4個應用程序組件可以獲得該ID。 Application類不在該列表中,並且由於我無論如何都需要服務,所以服務中的onCreate()是獲取Secure.Android_ID的PERFECT位置(對於我)。 – 2011-06-06 21:51:02

相關問題