NullPointerException异常将项目添加到列表时 [英] NullPointerException when adding an Item to the list

查看:107
本文介绍了NullPointerException异常将项目添加到列表时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

直升机所有,

我有我面临NullPointerException异常问题时,我想将项目添加到列表中,如下图所示:

I have a problem that I am facing NullPointerException when I want to add an item to the List, as shown below:

public List<SearchResponse> sortMPGListViewForNA(List<SearchResponse> response)
    {
        List<SearchResponse> list = response;
        List<SearchResponse> tempMPG = null, tempPrice = null, tempRating = null;
        for(int i=0;i<response.size();i++)
        {
            if(response.get(i).years.get(0).mpg.equalsIgnoreCase("n/a"))
            {
                tempMPG.add(response.get(i));
                list.remove(i);
            }
            if(response.get(i).years.get(0).price.equalsIgnoreCase("n/a"))
            {
                tempPrice.add(response.get(i));
                list.remove(i);
            }
            if(response.get(i).years.get(0).rating.equalsIgnoreCase("n/a"))
            {
                tempRating.add(response.get(i));//NPE Occurs Here
                list.remove(i);
            }
        }
        response.addAll(tempMPG);
        response.addAll(tempPrice);
        response.addAll(tempRating);
        return response;
    }

请给我建议的任何解决方案,就以相同的。

Please suggest me any solution regarding to the same.

在此先感谢。

推荐答案

您需要初始化tempMPG,tempPrice和tempRating:

You need to initialize tempMPG, tempPrice and tempRating:

tempMpg = new ArrayList<SearchResponse>();
tempPrice = new ArrayList<SearchResponse>();
tempRating = new ArrayList<SearchResponse>();

这篇关于NullPointerException异常将项目添加到列表时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆