Skip to content Skip to sidebar Skip to footer

Firebase : Can't Convert Object Of Type Java.lang.string To Type Com.example.g.model.cart

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 at com.google.fireb

Solution 1:

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.

Solution 2:

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));
}

Post a Comment for "Firebase : Can't Convert Object Of Type Java.lang.string To Type Com.example.g.model.cart"