5

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.

Community
  • 1
  • 1
kAmol
  • 1,297
  • 1
  • 18
  • 29

4 Answers4

11

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

Henry
  • 42,982
  • 7
  • 68
  • 84
2

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.

Ryan M
  • 18,333
  • 31
  • 67
  • 74
2

To get application context in a good way, you should use in following way.

Use following way

Step 1

Create an Application class

public class MyApplication extends Application{

    private static Context context;

    public void onCreate(){
        super.onCreate();
        MyApplication.context = getApplicationContext();
    }

    public static Context getAppContext() {
        return MyApplication.context;
    }
}

Step 2

In Android Manifest file declare following

<application android:name="com.xyz.MyApplication">
   ...
</application>

Step 3

Use following method to call Application context anywhere in your application.

MyApplication.getAppContext();

Like,

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

    public GCMNotificationIntentService() {
        super("GcmIntentService");
        mainContext = MyApplication.getAppContext();
        writeFile = new WriteFile(mainContext);
    }
    // My rest of the code
}
Chintan Rathod
  • 25,864
  • 13
  • 83
  • 93
0

Use GCMNotificationIntentService.this or simply this instead of mainContext.

IntentService extends Service which is itself a subclass of Context

Alex Chengalan
  • 8,211
  • 4
  • 42
  • 56