1

I am getting two type of responses from the server the first one in case of the routes is being sent to the server with the JSOn string then I get as response {"status":230,"routes":[1,9,3]} or not being sent then I get {"status":201}. Currently the app crashes if the response is {"status":201} and I am getting:

Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference

How can I prevent that? I want to do nothing if that the server response?

            Gson gson = new Gson();
            StopsJSON data = gson.fromJson(sb.toString(), StopsJSON.class);

            routes = data.getRoutes();

@Override
    protected void onPostExecute(Void result) {
        // Intent with Conetxt of the Asyntask class and
        Intent intent = new Intent(mContext, MainActivity.class);
        intent.putIntegerArrayListExtra("stop_route", routes);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        mContext.startActivity(intent);

    }

In MainActivity:

@Override
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub
        super.onNewIntent(intent);

        // getIntent() should always return the most recent
        setIntent(intent);

        Bundle extras = getIntent().getExtras();
        if (extras != null && extras.containsKey("stop_route")) {

            final ArrayList<Integer> routeList = extras
                    .getIntegerArrayList("stop_route");
            int routeListSize = routeList.size();
            if(routeListSize > 0){


    }
}
The Time
  • 697
  • 5
  • 12
  • 26
  • It's not enough to check that `extras` contains the key `"stop_route"`. You need to check that the array isn't `null`. The place to check for that is in `onPostExecute`, where you should not call `intent.putIntegerArrayListExtra("stop_route", routes);` if `routes` is `null`. – Ted Hopp May 22 '15 at 20:53

1 Answers1

2

It seems like routeList is equal to null

final ArrayList<Integer> routeList = extras.getIntegerArrayList("stop_route");
int routeListSize = routeList.size(); // Crash


@Override
protected void onPostExecute(Void result) {
    // Intent with Conetxt of the Asyntask class and
    if(routes != null){
       Intent intent = new Intent(mContext, MainActivity.class);
       intent.putIntegerArrayListExtra("stop_route", routes);
       intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
       mContext.startActivity(intent);
    }
    else
       Log.e("123", "Avoiding null pointer, the routes are null!!!");
 }
Bojan Kseneman
  • 15,488
  • 2
  • 54
  • 59