Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Context is null in service constructor?

My goal is to have a background service that update a fairly large amount of data twice a day (~5min update, possibly more).

So I have a GcmTaskService that launch this service :

public class SyncOfflineCoursesService extends Service {

    private final IBinder mBinder = new MonBinder();
    private final SharedPreferenceManagerToReplace sharedPreferenceManager;

    public SyncOfflineCoursesService() {

        sharedPreferenceManager = new SharedPreferenceManagerToReplace(this); //crash on this line

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    ...
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    public class MonBinder extends Binder {
        SyncOfflineCoursesService getService() {
            return SyncOfflineCoursesService.this;
        }
    }

}

SharedPreferenceManagerToReplace :

public class SharedPreferenceManagerToReplace {
    private final SharedPreferences prefs;

    public SharedPreferenceManagerToReplace(Context context) {
        this.prefs = PreferenceManager.getDefaultSharedPreferences(context);//crash here
    }
}

but it seem that this is null when I instanciate SharedPreferenceManager

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference

That's how I declared both of my services in my manifest :

<service
    android:name=".service.offline.SyncOfflineCoursesService"
    android:exported="false" />

<service
    android:name=".service.offline.SyncOfflineContentService"
    android:exported="true"
    android:permission="com.google.android.gms.permission.BIND_NETWORK_TASK_SERVICE">

    <intent-filter>
        <action android:name="com.google.android.gms.gcm.ACTION_TASK_READY" />
    </intent-filter>
</service>

Would you have an idea ?

Thanks !

like image 526
Renaud Favier Avatar asked Dec 18 '22 08:12

Renaud Favier


1 Answers

NullPointerException is thrown when an application attempts to use an object reference that has the null value.

You should call this in onStartCommand() Section .

 Context context;  //Public  

 @Override
    public int onStartCommand(Intent intent, int flags, int startId) 
    {
    context= getApplicationContext();
    sharedPreferenceManager = new SharedPreferenceManagerToReplace(context); 
    return super.onStartCommand(intent, flags, startId);
    }
like image 155
IntelliJ Amiya Avatar answered Dec 28 '22 08:12

IntelliJ Amiya