0

in the following code:

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() causes a NullPointerException. Why ?

I find this exception especially confusing because Google states "You get a ContentResolver by calling getContentResolver() from within the implementation of an Activity or other application component"

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

Someone Somewhere
  • 23,475
  • 11
  • 118
  • 166

2 Answers2

4

Do this when overriding oncreate better than in your constructor. I guess your app doesn't have a context yet.

Actually, here is what I did yesterday for some LVL code :

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

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

And it works like a charm...

Snicolas
  • 37,840
  • 15
  • 114
  • 173
  • it does work properly in an Activity.onCreate(), but the Application constructor seemed like a handy spot because I wanted to lookup some data only once for every launch. – Someone Somewhere Jun 03 '11 at 22:03
  • `onCreate()` only happens once per launch. You should never need to put functionality in an Activity's constructor. Read [this](http://developer.android.com/guide/topics/fundamentals/activities.html#Lifecycle). – Gyan aka Gary Buyn Jun 03 '11 at 22:16
  • The Application must have context because it extends ContextWrapper which extends Context. – Someone Somewhere Jun 05 '11 at 08:20
  • accepted answer because onCreate() is the best place for this - be it in an activity or service, or whatever. – Someone Somewhere Jun 06 '11 at 21:54
0

The "Application" class is not an "Application Component". http://developer.android.com/guide/topics/fundamentals.html#Components

To solve this problem, my plan is to grab the ANDROID_ID from within a service.

Someone Somewhere
  • 23,475
  • 11
  • 118
  • 166
  • What do you mean by The application class in not an application component. I don't think you need an additionnal process like a service to get the ANDROID_ID... – Snicolas Jun 05 '11 at 11:46
  • in that list, the 4 application components can get the ID. The Application class is not in that list, and since I needed a service anyway the onCreate() within the service is the PERFECT spot (for me) to get the Secure.Android_ID. – Someone Somewhere Jun 06 '11 at 21:51