Pregunta

I want to run through an ArrayList<Object> which contains some ArrayList of different types. But each type is extended by ItemProperties with basic information about the type like name and picture (.getName() and .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);
        }
    }

How can I get this to work?

¿Fue útil?

Solución 3

I have a few suggestions for improving your current code. Rather than defining a List of Objects to hold your lists, you can type it more strongly by using the following syntax:

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

So now when you loop through your list you don't have to type cast your elements in the for-each loop.

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

Otros consejos

The NullPointerException will not have anything to do with the way you have set up your lists. However, if you what you say is correct, that the first list will contain lists which in turn will all contain elements extending ItemProperties then you should type your lists for that.

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

The NullPointerException occurs when you declare a variable but did not create an object. This exception occurs when you try to use a reference that points to no location in memory as though it were referencing an object.

NullPointerException is itself enough to tell you that you haven't initialized the ArrayList properly. If you still have a problem, post stackTrace().

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top