Add items to an Expandable List

0

I'm trying to use an Expandable List. In this Expandable List I want to put "my product categories" as a header and "my products" in my children items. However I am getting the error " java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1 ", when I try to insert the products the categories (headers). Both the products and the categories I get from my database.

LinkedHashMap <String, List<String>> expandableListDetail2 = new LinkedHashMap<String, List<String>>();

        List<String> categoria_header = new ArrayList<String>();
        int i=0;
        List<Producto> produtos;
        Database db = new Database(context);
        List<Categorias> categorias;

        categorias = db.getAllCategorias();

        for (i=0; i<categorias.size(); i++){

            expandableListDetail2.put(categorias.get(i).toString(), categoria_header);

            produtos = db.getAllProductos(categorias.get(i).toString());

               for(int j=0;j<produtos.size();j++) {
                   Log.d("Expandable","categoria->"+categorias.get(i).toString());
                   Log.d("Expan","get->"+produtos.get(0).getNomeProducto());
                   categoria_header.add(i,produtos.get(j).getNomeProducto());
               }
}

The problem is in produtos.get(j).getNomeProducto() . Can anyone help?

    
asked by anonymous 26.10.2015 / 20:03

1 answer

0

The error happens when you add() in the category_header list. If the first category has no products, nothing is put in the list, the i is incremented, it changes to 1 , when it tries to add with i = 1 it gives error because i can not be greater than size from the list.

If I understand what you want to do, change the code like this:

LinkedHashMap <String, List<String>> expandableListDetail2 = new LinkedHashMap<String, List<String>>();

    int i=0;
    List<Producto> produtos;
    Database db = new Database(context);
    List<Categorias> categorias;

    categorias = db.getAllCategorias();

    for (i=0; i<categorias.size(); i++){

        List<String> categoria_header = new ArrayList<String>();

        produtos = db.getAllProductos(categorias.get(i).toString());

       for(int j=0;j<produtos.size();j++) {
           Log.d("Expandable","categoria->"+categorias.get(i).toString());
           Log.d("Expan","get->"+produtos.get(0).getNomeProducto());
           categoria_header.add(produtos.get(j).getNomeProducto());
       }

        expandableListDetail2.put(categorias.get(i).toString(), categoria_header);

    }
}

The expandable HashMapListDetail2 should receive a new category_header list for each category. Therefore, a new object must be created within the cycle for(i=0; i<categorias.size(); i++)

Note: I think you should change the name category_header to categoryProducts     

26.10.2015 / 21:15