简体   繁体   中英

Starting IntentService throws NullpointerException and onHandleIntent() is never called

this is actually my first question on stackoverflow and I hope I will get this right.

I got a really frustrating problem with my Broadcastreceiver starting an IntentService, because as the title says, startService() throws a NullpointerException at me and I just can't find the reason while debugging. The stacktrace as just gives me the line where it is caused (caused by startService()) and I already set breakpoints inside the onHandleIntent() method from the service, but this is never called.

I declared the receiver and the service in the manifest as described in the android api doc.

here are my two classes:

public class NetworkBroadcastReceiver extends BroadcastReceiver {

    private static final String LOG_TAG = NetworkBroadcastReceiver.class.getSimpleName();

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

        ConnectivityManager cm =
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null &&
            activeNetwork.isConnectedOrConnecting();

        if (isConnected) {

            try {
                Intent uselessIntent = new Intent();
                IntentService syncService = new SyncService();

                 syncService.startService(uselessIntent);
            }catch (NullPointerException npe){
                npe.printStackTrace(System.err);
            }
        }
    }
}

public class SyncService extends IntentService {

    public SyncService() {
        super(SyncService.class.getSimpleName());
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
            JamDbHelper dbHelper = new JamDbHelper(this);
            Cursor routes = dbHelper.getAllRoutes();

            while (routes.moveToNext()) {

                int synced = routes.getInt(routes.getColumnIndex(DataBaseContract.RouteEntry.COLUMN_SYNC));
                if (synced == 0) {

                    int routeId = routes.getInt(routes.getColumnIndex(DataBaseContract.RouteEntry._ID));
                    int userId = routes.getInt(routes.getColumnIndex(DataBaseContract.RouteEntry.COLUMN_USERID));
                    String startDate = routes.getString(routes.getColumnIndex(DataBaseContract.RouteEntry.COLUMN_STARTDATE));
                    String endDate = routes.getString(routes.getColumnIndex(DataBaseContract.RouteEntry.COLUMN_ENDDATE));

                    Route route = new Route(routeId, userId, startDate, endDate);
                    Cursor coords = dbHelper.getRoute((long) routeId);

                    while (coords.moveToNext()) {

                        double longitude = coords.getDouble(coords.getColumnIndex(DataBaseContract.CoordsEntry.COLUMN_LONG));
                        double latitude = coords.getDouble(coords.getColumnIndex(DataBaseContract.CoordsEntry.COLUMN_LAT));
                        float speed = coords.getFloat(coords.getColumnIndex(DataBaseContract.CoordsEntry.COLUMN_SPEED));
                        int jammed = coords.getInt(coords.getColumnIndex(DataBaseContract.CoordsEntry.COLUMN_JAM));

                        route.putWaypoint(new Waypoint(longitude, latitude, speed, jammed));

                    }

                    Uri basicUri = HttpHandler.buildBasicURI(this);
                    String url = basicUri.toString();

                    String json = new Gson().toJson(route);

                    String enc = "UTF-8";
                    String post_data = null;
                    try {
                        post_data = URLEncoder.encode("api", enc) + "=" + URLEncoder.encode("postRoute", enc) + "&"
                            + URLEncoder.encode("json", enc) + "=" + URLEncoder.encode(json, enc);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }

                    if (HttpHandler.isOnline(this)) {

                        HttpHandler httpHandler = new HttpHandler();
                        String result = httpHandler.makePOSTServiceCall(url, post_data);

                        StateObject state = new Gson().fromJson(result, StateObject.class);

                        if (state.getState().equals(this.getString(R.string.success))) {
                        dbHelper.setSynced(routeId);

                        }
                    }

                }
            }
    }
}

I would be very grateful for help and since this is my first question, just ask straight away if you need more information, thank you!

I've altered your code for starting your Service correctly.

public class NetworkBroadcastReceiver extends BroadcastReceiver {

    private static final String LOG_TAG = NetworkBroadcastReceiver.class.getSimpleName();

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

        ConnectivityManager cm =
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null &&
                activeNetwork.isConnectedOrConnecting();

        if (isConnected) {

            try {
                Intent uselessIntent = new Intent(context, SyncService.class);
                context.startService(uselessIntent);
            }catch (NullPointerException npe){
                npe.printStackTrace(System.err);
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM