Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting getApplicationcontext() null?

I'm not sure whats wrong in it! I read here that Intentservice is itself a subclass of Context.

public class GCMNotificationIntentService extends IntentService {
    private NotificationManager mNotificationManager;
    NotificationCompat.Builder builder;
    Context mainContext;
    WriteFile writeFile;

    public GCMNotificationIntentService() {
        super("GcmIntentService");
        mainContext = getApplicationContext();
        writeFile = new WriteFile(mainContext);
    }
    // My rest of the code
}

but I'm getting null value for mainContext. Any suggestions are most welcome.

like image 650
kAmol Avatar asked Sep 17 '15 05:09

kAmol


2 Answers

In the constructor it is way too early to access the app context. Try to move this code into the onCreate method.

More datails about the life cycle can be found in the documentation

like image 57
Henry Avatar answered Sep 18 '22 23:09

Henry


You should be calling this in your onCreate method, not the constructor. In the constructor, the application context has not been set up yet, so it will be null.

like image 22
Ryan M Avatar answered Sep 19 '22 23:09

Ryan M