Pallav
Pallav

Reputation: 165

Starting A service from a Broadcast Receiver

Iam trying to start a service,which updates some data to spreadsheet, from a broadcast receiver. But Iam getting an Error that says UNABLE TO INSTANTIATE SERVICE : NULL POINTER EXCEPTION. My Receiver code is:

    import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.widget.Toast;

/**
 * Created by Pallav on 4/27/2015.
 */
public class InternetReciever extends BroadcastReceiver {

    @Override
    public void onReceive( Context context, Intent intent) {

        if (isOnline(context)) {
            Toast.makeText(context, "Network Available Do operations", Toast.LENGTH_LONG).show();
            Intent updateIntent = new Intent(context, UpdateToSpreadsheet.class);
            context.startService(updateIntent);
        }

    }


    public boolean isOnline(Context context) {

        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        //should check null because in air plan mode it will be null
        return (netInfo != null && netInfo.isConnected());

    }
}

The code for my Service is:

public class UpdateToSpreadsheet extends Service {
D

BAdapter db;
    Cursor c = db.getAllContacts();


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

    @Override
    public void onCreate() {
        super.onCreate();
        //some code
}

I have registered the Service and the Receiver in the Manifest file and have added all the permissions.The receiver is also working fine.I am confused what is the Problem with my Code. Please help me out.

Upvotes: 0

Views: 63

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006584

In the future, please examine LogCat to see where you are crashing.

In this case, Der Golem would appear to be correct. Not only are you attempting to do database I/O on the main application thread (bad!), you are trying to do so in an initializer of the Service. db is null, and so you cannot call methods on db.

You are going to need to move your db.getAllContacts() call into the body of your service, after db has been initialized, and on a background thread.

Upvotes: 2

Related Questions