在以下代码:为什么应用程序中的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