简体   繁体   中英

Get ArrayList in Firestore - Android

I am creating an Android app that needs to access a document which has an ArrayList in it.

I took a look at this link Check This Stack Overflow Answer.

I tried everything I could. The guy even gave the answer that we should do (ArrayList<String>) documentSnapshot.get("key") . I tried doing that but when I do, I get this error from Android Studio: Unchecked cast: 'java.lang.Object' to 'java.util.ArrayList<java.lang.String>' . It's also asking me to generify my class.

This is my Firestore structure.

这是我的 Firestore 结构。

This is my code till now:

DocumentReference docRef = firestore.collection("Users").document(fullMobile);
                docRef.get().addOnCompleteListener(task -> {
                    if (task.isSuccessful()) {
                        DocumentSnapshot document = task.getResult();
                        assert document != null;
                        // Data from FireStore
                        ArrayList<String> devices = (ArrayList<String>) document.get("Devices"); ----- This is the line which is wrong.
                        if (document.exists()) { // LOGIN
                            // Some Code
                        } else { // SIGNUP
                           // Some Code
                        }
                    } else {
                        toast("An Error Occured! Please Try Again");
                    }
                });

I don't know what to do know. Can someone please help me?

If your document contains array of data,Create arraylist then add item.

ArrayList<String> devices = new ArrayList<>();
devices.add(document.get("Devices"));

If your document contains custom object (model class), use same model class to get it back.

 for (DocumentSnapshot document : snapshots.getDocuments()) {
            String documentkey = document.getId();
             UsedCarDetailsModel usedCarDetailsModel = document.toObject(UsedCarDetailsModel.class);
             documentList.add(usedCarDetailsModel);

        }

If you are beginner, just place cursor on warning text then press Alt+Enter,Android studio will show available option to cast your document. choose suitable one for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM