Firebase : Can't convert object of type java.lang.String to type com.example.g.Model.Cart

后端 未结 2 1203
难免孤独
难免孤独 2021-01-16 16:34

I had error that said

com.google.firebase.database.DatabaseException: Can\'t convert object of type java.lang.String to type com.example.g.Model.Cart

相关标签:
2条回答
  • 2021-01-16 17:07

    You have two nested loops in your onDataChange:

    CartList = new ArrayList<>();
    for (DataSnapshot ds : dataSnapshot.getChildren()) {
        for (DataSnapshot cart : ds.getChildren()) {
            CartList.add(cart.getValue(Cart.class));
        }
    }
    

    But if I look at the JSON at the location you attach the listener to, I see only the date level. So in that case, you need only one loop:

    CartList = new ArrayList<>();
    for (DataSnapshot cart : dataSnapshot.getChildren()) {
        CartList.add(cart.getValue(Cart.class));
    }
    

    The nested loop would only be needed if a user could have multiple carts per day, but your current data model only allows one cart per day.

    0 讨论(0)
  • 2021-01-16 17:09

    From your code it looks like you are iterating a layer too deep in your structure. Easy Fix: Replace

    for (DataSnapshot ds : dataSnapshot.getChildren()) {
        for (DataSnapshot cart : ds.getChildren()) {
             CartList.add(cart.getValue(Cart.class));
        }
    }
    

    with

    for (DataSnapshot cart : dataSnapshot.getChildren()) {
         CartList.add(cart.getValue(Cart.class));
    }
    
    0 讨论(0)
提交回复
热议问题