Void method returns items to the list, but when I try to use this list, it is empty!

Asked

Viewed 26 times

0

 listaPedidoComprador.setLayoutManager(new LinearLayoutManager(this));
    listaPedidoComprador.setHasFixedSize(true);
    adapterPedidoComprador = new AdapterPedidoComprador(itensCarrinho2);
    System.out.println(String.format("quantidade que está no itensCarrinho pro adapter:  %d ", itensCarrinho.size()));
    listaPedidoComprador.setAdapter(adapterPedidoComprador);
    adapterPedidoComprador.setOnItemClickListener(new AdapterPedidoComprador.OnItemClickListener() {
        @Override
        public void onAddClick(int position) {
            ItemPedido itemPedido = itensCarrinho2.get(position);
            Toast.makeText(CompradorPedidos.this, itemPedido.getNomeProduto(), Toast.LENGTH_SHORT).show();
        }
    });
    recuperarItemPedidoJamilton();

    System.out.println(String.format("pedidos recuperados: %d", produtos.size()));
    System.out.println(String.format("quantidade que está no carrinho:  %d nesse exato momento fora do método", itensCarrinho.size()));
    System.out.println(String.format("quantidade que está no carrinho2:  %d nesse exato momento fora do método", itensCarrinho2.size()));
    System.out.println("eae bb");

}

@Override
protected void onStart() {
    super.onStart();
    //recuperarItemPedidoJamilton();
}

private void recuperarItemPedidoJamilton() {
    DatabaseReference produtoref = firebaseRef
            .child("pedidos_usuario")
            .child(idUsuarioLogado);

    produtoref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if (dataSnapshot.getValue() != null) {
                pedidoRecuperado = dataSnapshot.getValue(Pedido.class);
                itensCarrinho2 = pedidoRecuperado.getItens();
                adapterPedidoComprador.notifyDataSetChanged();
                System.out.println(String.format("quantidade que está no carrinhoJamilton:  %d nesse exato momento", itensCarrinho2.size()));
            } else {
                //Toast.makeText(CompradorPedidos.this, "Seu carrinho está vazio", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            // Error
        }

    });
    System.out.println(String.format("quantidade que está no carrinhoJamiltonfora:  %d nesse exato momento", itensCarrinho.size()));

}

As you can see, I’m trying to put this list on the Adapter, but it’s not right because this list is apparently empty. I do not understand what is happening, since I put a println inside the method and it is returning that there are items inside the list!!

I have tried to leave itensCarrinho2 (list I am trying to fill) static, but I can’t work well so there are cases where it is necessary to delete the list, because it is a shopping cart, and when confirming or removing an item from the cart, cannot be removed from the list that is static... I suppose...

  • Hello. Please, detail better the situation that is happening. I understand that you have added a list to Adapter that should initially be empty, and are not adding the new item to it before calling notifyDataSetChanged() Adapter.

  • I’m trying to put the itensCarrinho2 list to my Adapter, as you can see in the code, I call a method to fill this list (recoveryItemPedidoJamilton();) and I know that this list is being filled in by the println I put inside (it shows that there are items in the list using itensCarrinho2.size.), but by the time I call pro Adapter, it is empty

1 answer

0


I get it now.

Well, understand that itensCarrinhos2 is a reference to a list object, not the object itself. You passed this reference to Adapter and it does not expect it to be changed, just to change the content of the object itself (i.e., the contents of the list).

So when you do itensCarrinho2 = pedidoRecuperado.getItens(); you point this variable to another object, in the case to what is being returned by getItens(), only when it calls notifyDataSetChanged() the Adapter does not know this and checks the object pointed by the reference passed to it previously, which has not changed.

Remember that in Java the arguments are always passed "by value", that is, a copy of the argument is being passed, in this case the reference to the list, and Adapter starts to store a copy of this reference internally. While the two are pointing to the same great object, everything works, but you changed it in your code when you did itensCarrinho2 point to another object.

The solution therefore is to either change the content of the list by the very reference the Adapter already knows:

itensCarrinho2.clear();
itensCarrinho2.addAll(pedidoRecuperado.getItens());
adapterPedidoComprador.notifyDataSetChanged();

...or else look for a method in the Adapter class/base interface that allows updating the reference that was passed to the Adapter, a setDataSet() of life or something, I don’t remember if you have a.

  • 1

    "Remember that in Java arguments are always passed "by reference"" Look, I remember the values in java are always "pass-by-value", Can you confirm that, just in case? has even asked this in the OS: https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value

  • 1

    @Ricardopunctual Pardon, I always confuse the two terms. You’re right, it’s worth even, already corrected. So I particularly like to say "by copying".

  • THANK YOU!!!!!!! <3 worked out right here :') Thanks a lot @Piozevan, really even !!!!

  • @Joãovitor Do the [tour]

  • @While speaking "by copying", if you do not know that the reference is only pointing to the object and it is not the object itself will remain ambiguous in the same way.

  • yes, this may confuse. I prefer how it is said in C#, "by value" and "by Reference", it seems to me that it is clearer at least to understand

Show 1 more comment

Browser other questions tagged

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