简体   繁体   English

在 Firestore 中获取 ArrayList - Android

[英]Get ArrayList in Firestore - Android

I am creating an Android app that needs to access a document which has an ArrayList in it.我正在创建一个 Android 应用程序,该应用程序需要访问其中包含 ArrayList 的文档。

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") .这家伙甚至给出了我们应该做的答案(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>' .我尝试这样做,但是当我这样做时,我从 Android Studio: Unchecked cast: 'java.lang.Object' to 'java.util.ArrayList<java.lang.String>'收到此错误。 It's also asking me to generify my class.它还要求我生成我的 class。

This is my Firestore structure.这是我的 Firestore 结构。

这是我的 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 然后添加项目。

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.如果您的文档包含自定义 object(模型类),请使用相同的 model class 将其取回。

 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.如果您是初学者,只需将 cursor 放在警告文本上,然后按 Alt+Enter,Android 工作室将显示可用选项来投射您的文档。 choose suitable one for you.选择适合您的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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