在以下代碼:爲什麼應用程序中的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
它在Activity.onCreate()中可以正常工作,但是應用程序構造函數看起來很方便,因爲我想每次啓動時只查找一次數據。 – 2011-06-03 22:03:54
'onCreate()'只在每次啓動時發生一次。你永遠不需要在一個Activity的構造函數中放入功能。閱讀[this](http://developer.android.com/guide/topics/fundamentals/activities.html#Lifecycle)。 – 2011-06-03 22:16:51
應用程序必須具有上下文,因爲它擴展了擴展上下文的ContextWrapper。 – 2011-06-05 08:20:15