繁体   English   中英

数组列表空指针异常-Android

[英]Array List Null Pointer Exception - Android

我试图创建一个可检索用户喜欢的书报价的应用程序,但是我仍然坚持如何将这些信息显示给用户。 我创建了一个ArrayList来存储所有信息。 但是,在显示此信息时,我不断收到错误消息:

java.lang.NullPointerException

当它尝试执行代码时

temp[i] = new HashMap<String,String>();

此类如下所示:

public class FavouriteQuotesActivity extends ListActivity {

    static final ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();

    private void getFavorites() {
        DataBaseHelper myDbHelper = new DataBaseHelper(this);

        String favorites [] = myDbHelper.getFavourites();

        if(list.size() > 0)
        {
            list.removeAll(list);
        }

        for(int i = 0;i < favorites.length; i++)
        {
            String quotes = favorites[i];
            String[] quoteArray = quotes.split(":");
            HashMap<String,String> temp[] = null; 

            temp[i] = new HashMap<String,String>();
            temp[i].put("Author",(quoteArray[2]));
            temp[i].put("Quote",(quoteArray[4]));
            list.add(temp[i]);

        }


    }

任何帮助将不胜感激。

看下面的代码:

HashMap<String,String> temp[] = null; 
temp[i] = new HashMap<String,String>();

刚刚temp变量分配了一个空值(通常会有一个HashMap<String, String>[] temp )-因此,当您尝试访问temp[i]时,您当然会得到NullPointerException temp[i]在下一个语句中。

目前尚不清楚为什么在该代码中完全使用数组-为​​什么不仅仅使用:

HashMap<String, String> map = new HashMap<String, String>();
map.put("Author", quoteArray[2]);
map.put("Quote", quoteArray[4]);
list.add(map);

另外,由于地图始终具有相同的两个键,因此尚不清楚您为什么在这里使用地图。 为什么不使用名称和作者属性创建Quote类? 另外,在这里使用静态变量似乎是个坏主意-为什么getFavorites不会在每次调用时创建一个新列表,并在方法末尾将其返回?

temp不指向数组。 您将其设置为null

您将变量temp声明为数组(通过编写HashMap temp[] )。

如果不是实际数组,则无法设置任何元素。

您声明并使用temp错误。 您不需要一个HashMap数组,只需一个HashMap ,因为listArrayList<HashMap>

HashMap<String,String> temp = new HashMap<String,String>();
temp.put("Author",(quoteArray[2]));
temp.put("Quote",(quoteArray[4]));
list.add(temp);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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