2011-06-03 157 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

相关问题