Home > OS >  Retrieving ArrayList of Custom objects in firebase
Retrieving ArrayList of Custom objects in firebase

Time:04-06

How would you go about storing and retrieving an ArrayList of custom objects in firebase? In my android application, I store and retrieve an array as follows

Storage:

ArrayList<GameQRCode> qrCodes = new ArrayList<>();
qrCodes.add(new GameQRCode("name1", "value1"));
qrCodes.add(new GameQRCode("name2", "value2"));
qrCodes.add(new GameQRCode("name3", "value3"));
User user = new User("myUsername");
user.setQrCodes(qrCodes);

db.collection("users").document("myUsername").set(user);

Retrieval:

db.collection("users").document("myUsername").get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                ArrayList<GameQRCode> testList = (ArrayList<GameQRCode>) task.getResult().get("qrCodes");
            }
        });

However, when I try to use the retreived ArrayList, I get an error message like follows...

GameQRCode qrCode = qrCodes.get(position);

java.util.HashMap cannot be cast to com.example.qracutie.GameQRCode

Your help is greatly appreciated

CodePudding user response:

Firestore doesn't remember the type of custom object you used to in your collection generic type, so you can't simply cast it the way you put it in after you get the document back. The error message is telling you that it stored data as a Map instead of your custom object type. It will be your responsibility to deal with that Map directly, pulling values out of it and mapping them back into your custom object. This means that you should probably pull data out like this:

List<Map<String, Object> testList =
   (List<Map<String, Object>>) task.getResult().get("qrCodes");

In fact, you should be aware that Firestore will internally map everything to one of these basic types: Map, List, String, Integer/Long, Boolean, null. You should expect to get only these types, and you should probably also check the types of instanceof before you cast anything at all, in order to make sure that you never make an incorrect cast at runtime.

  • Related