Loop on an Object with an array variable

Asked

Viewed 179 times

-2

    {
        List<PedidosPendentesOBJ> listaPedidos = new ArrayList<>();
        List<ProdutosPendentes> produtosList = null;

        JSONObject o = new JSONObject(ret);
        JSONArray ts = o.names();

        for (int i = 0; i < ts.length(); i++) {

            String token = ts.getString(i);
            JSONObject p = o.getJSONObject(token);
            String cliente = p.getString("Cliente");

            JSONArray Produtos = p.getJSONArray("Produtos");

            for (int ii = 0; ii < Produtos.length(); ii++) {
                // ESSE ARRAY DEVE SER CHAMADO COMO NOVO, TODA VEZ QUE PASSAR NO LOOP
                produtosList = new ArrayList<>();
                JSONObject objPro = Produtos.getJSONObject(ii);
                String descricao = objPro.getString("descricao");
                double valor = objPro.getDouble("valor");
                produtosList.add(new ProdutosPendentes(descricao, valor, quanti));
            }
            // AQUI EU ADICIONO NA LISTA, QUE CADA OBJETO DEVERIA TER SUA VARIÁVEL DIERENTE CADA UM
            listaPedidos.add(new PedidosPendentesOBJ(token, cliente, valorTotal, status, data, produtosList));
        }
        return listaPedidos;
    }

I’m populating a ArrayList with several objects with structure for. However one of the variables is an array, that is the problem, when the loop passes through the Object it enters the loop of the variable array, and instead of it creating a list array for each object, it creates only one and adds in all objects in the same array list.

I want to create a new array list of the object each time the loop passes through the object.

  • You could clear a little code and leave only what is needed to solve the problem?

  • I edited and tried to put as little as possible, thanks for the feedback

  • produtosList = new ArrayList<>(); should stay before the loop, so I understand what you want.

  • I DID IT. Thank you all! The Resolution was as follows: I was using the different Adapters, so this was causing error at the time of popular the List, so I switched to another Adapter and solved the problem, I just had to change the new Arraylist<>() out of the second loop.

1 answer

2

From what I understand, you are creating an array with only 1 object always.

Place produtosList = new ArrayList<>(); before your second loop, this way you create a product list when you go through the second loop.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.