尝试在空对象引用上调用虚方法'int java.util.ArrayList.size()'

时间:2015-05-22 20:48:51

标签: android

我从服务器得到两种类型的响应,如果routes被发送到带有JSOn字符串的服务器然后我得到响应{"status":230,"routes":[1,9,3]}或者没有被发送我得到{"status":201}。目前,如果响应为{"status":201}并且我收到了应用程序,则应用程序崩溃:

  

尝试在空对象引用上调用虚方法'int java.util.ArrayList.size()'

我该怎样防止这种情况?如果服务器响应,我想什么都不做?

            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);

    }

在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){


    }
}

1 个答案:

答案 0 :(得分:2)

似乎routeList等于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!!!");
 }