【问题标题】:ArrayList<Object> contains different ArrayLists NullpointerArrayList<Object> 包含不同的ArrayLists Nullpointer
【发布时间】:2014-07-02 17:40:19
【问题描述】:

我想运行一个 ArrayList ,其中包含一些不同类型的 ArrayList。但是每个类型都由 ItemProperties 扩展,并带有关于类型的基本信息,例如名称和图片(.getName() 和 .getPicture())。

ArrayList<Object> lists = new ArrayList<Object>();
lists.add(listType1); //Class Type1 extends ItemProperties
lists.add(listType2); //Class Type2 extends ItemProperties
lists.add(listType3); //Class Type3 extends ItemProperties

for (Object o : lists) {
    ArrayList<ItemProperties> al = (ArrayList<ItemProperties>) o;
    for (ItemProperties p : al) { //Nullpointer Exception here
        if (getString(p.getName()).toLowerCase().contains(arg0.toLowerCase())) {
            Drawable icon = getResources().getDrawable(p.getPicture());
            TextView tv = new TextView(this);
            tv.setTextSize(20);
            tv.setTextColor(Color.WHITE);
            tv.setGravity(Gravity.CENTER_VERTICAL);
            tv.setText(p.getName());
            ll.addView(tv); //LinearLayout ll
            icon.setBounds(0, 0, tv.getLineHeight() * 3, tv.getLineHeight() * 3);
            tv.setCompoundDrawables(icon, null, null, null);
        }
    }

我怎样才能让它工作?

【问题讨论】:

  • 你遇到了什么异常?
  • 第 7 行的空指针
  • 您的列表是否有可能为空?
  • 不,我检查了很多次。
  • 好吧,如果你给我们第 7 行,那么应该不难弄清楚那行是什么给了你 NPE。或上下文中使用的其余代码。

标签: java android object arraylist


【解决方案1】:

NullPointerException 与您设置列表的方式没有任何关系。但是,如果您说的是正确的,那么第一个列表将包含列表,而这些列表又将包含扩展 ItemProperties 的元素,那么您应该为此键入您的列表。

List<List<ItemProperties>> lists = new ArrayList<List<ItemProperties>>();

【讨论】:

    【解决方案2】:

    我有一些改进您当前代码的建议。与其定义一个对象列表来保存您的列表,不如使用以下语法更强大地键入它:

    ArrayList< ArrayList<? extends ItemProperties> > lists = new ArrayList<>();
    

    因此,现在当您遍历列表时,您不必在 for-each 循环中输入元素。

     for (ArrayList<? extends ItemProperties> o : lists) {
         // Do something
     }
    

    【讨论】:

    • 感谢您的提示,但我的一些列表是多次扩展的。例如:Type1 扩展 xy 扩展 ItemProperties。我的代码目前实际上运行良好。我现在只需要弄清楚如何使用 onClick 打开它们。
    • 即使它的多重扩展这个成语适用于你的情况,只要你只想在你的 for 循环中使用 ItemProperties 中定义的方法
    • 1) 您描述了错误的列表,第一个列表包含列表,在他的示例中为 ArrayList。 2)你不能使用 以实现此功能,因为它不允许您添加元素,因此仅使用我描述的 ItemProperties 将是正确的方法。更多信息:stackoverflow.com/questions/2723397/java-generics-what-is-pecs
    • 我希望您阅读我编辑的评论,因为如果您尝试向 列表。
    • @Nicklas Gnejs Eriksson 非常感谢您的评论。我更改了代码以反映它。很抱歉这么晚才添加这个注释,因为我在睡眠模式下修改了代码:P
    【解决方案3】:

    NullPointerException 在您声明变量但未创建对象时发生。当您尝试使用指向内存中任何位置的引用时,就会发生此异常,就像它引用一个对象一样。

    NullPointerException 本身就足以告诉您您没有正确初始化 ArrayList。如果仍有问题,请发帖stackTrace()

    【讨论】:

      猜你喜欢
      • 2014-01-18
      • 2021-06-11
      • 1970-01-01
      • 2015-05-02
      • 2012-11-14
      • 2013-12-05
      • 1970-01-01
      • 1970-01-01
      • 2011-09-09
      相关资源
      最近更新 更多