Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Log.e(“三”,list.get(2)); query1=list.get(0);//在这个变量中,字符串与它们一起存储,然后您可以在Firestore中进行常规查询以获取实际文档 query2=list.get(1); query3=list.get(2); }捕获(例外e){ e、 printStackTrace(); } }_Java_Android_Firebase_Google Cloud Firestore - Fatal编程技术网

Java Log.e(“三”,list.get(2)); query1=list.get(0);//在这个变量中,字符串与它们一起存储,然后您可以在Firestore中进行常规查询以获取实际文档 query2=list.get(1); query3=list.get(2); }捕获(例外e){ e、 printStackTrace(); } }

Java Log.e(“三”,list.get(2)); query1=list.get(0);//在这个变量中,字符串与它们一起存储,然后您可以在Firestore中进行常规查询以获取实际文档 query2=list.get(1); query3=list.get(2); }捕获(例外e){ e、 printStackTrace(); } },java,android,firebase,google-cloud-firestore,Java,Android,Firebase,Google Cloud Firestore,以下是我从Firestore获得的阵列: 我遇到了一个类似的问题(我只需要每24小时获取一个随机文档,或者当用户手动刷新页面时,但您也可以将此解决方案应用到您的案例中),对我有效的方法如下: 技巧 第一次阅读一小份文档列表,比如1到10个文档(在您的情况下是10到30或50个) 根据文档列表范围内随机生成的数字选择随机文档 在客户端设备上本地保存您选择的文档的最后一个id(可能像我一样在共享首选项中) 如果您想要一个新的随机文档,您将使用保存的文档id在保存的文档id之后再次启动流程(步骤1至3

以下是我从Firestore获得的阵列:

我遇到了一个类似的问题(我只需要每24小时获取一个随机文档,或者当用户手动刷新页面时,但您也可以将此解决方案应用到您的案例中),对我有效的方法如下:

技巧
  • 第一次阅读一小份文档列表,比如1到10个文档(在您的情况下是10到30或50个)
  • 根据文档列表范围内随机生成的数字选择随机文档
  • 在客户端设备上本地保存您选择的文档的最后一个id(可能像我一样在共享首选项中)
  • 如果您想要一个新的随机文档,您将使用保存的文档id在保存的文档id之后再次启动流程(步骤1至3),这将排除之前出现的所有文档
  • 重复此过程,直到保存的文档id之后没有更多文档,然后从头开始重新开始,假设这是您第一次运行此算法(通过将保存的文档id设置为null,然后再次启动此过程(步骤1至4)
  • 技术利弊 优点:

  • 您可以在每次获得新的随机文档时确定跳转大小
  • 无需修改对象的原始模型类
  • 无需修改您已经拥有或设计的数据库
  • 无需在集合中添加文档,也无需在向集合中添加新文档时为每个文档添加随机id,就像前面提到的解决方案一样
  • 无需加载大的文档列表即可获得一个文档或小的文档列表
  • 如果您使用firestore自动生成的id,则效果良好(因为集合中的文档已经稍微随机化了)
  • 如果您想要一个随机文档或一个小规模的随机文档列表,那么这种方法非常有效
  • 适用于所有平台(包括iOS、Android、Web)
  • 缺点

  • 处理保存文档id以在下一个获取随机文档的请求中使用(这比处理每个文档中的新字段或处理将集合中每个文档的id添加到主集合中的新文档要好)
  • 如果列表不够大(在我的情况下,这不是一个问题),并且我没有找到任何可以完全避免此情况的解决方案,则可能会多次获取一些文档
  • 实现(android上的kotlin):
    var documentId=//从共享首选项获取文档id(如果之前未设置,则为空)
    getRandomDocument(文档ID)
    有趣的getRandomDocument(documentId:String?){
    if(documentId==null){
    val query=FirebaseFirestore.getInstance()
    .集合(集合名称)
    .limit(getLimitSize())
    loadDataWithQuery(查询)
    }否则{
    val docRef=FirebaseFirestore.getInstance()
    .集合(集合名称).文档(文档ID)
    docRef.get().addOnSuccessListener{documentSnapshot->
    val query=FirebaseFirestore.getInstance()
    .集合(集合名称)
    .startAfter(文档快照)
    .limit(getLimitSize())
    loadDataWithQuery(查询)
    }.addOnFailureListener{e->
    //处理失败
    }
    }
    }
    fun loadDataWithQuery(查询:查询){
    query.get().addOnSuccessListener{queryDocumentSnapshots->
    val documents=queryDocumentSnapshots.documents
    if(documents.isNotEmpty()&&documents[documents.size-1].exists()){
    //从加载的列表中选择一个文档(我选择了列表中的最后一个文档)
    val快照=文档[documents.size-1]
    var documentId=snapshot.id
    //在此共享首选项中保存文档id
    //在这里处理随机文件
    }否则{
    //在到达文档列表末尾时进行处理
    //所以我们重新开始,因为这是我们第一次得到一个随机文档
    //通过调用带有null作为documentId的getRandomDocument()
    getRandomDocument(空)
    }
    }
    }
    fun getLimitSize():长{
    val random=random()
    val listLimit=10
    return(random.nextInt(listLimit)+1.toLong()
    }
    
    基于我为Unity3D写的这篇文章及其对我的作用

    FirebaseFirestore db;
    
        void Start()
        {
            db = FirebaseFirestore.DefaultInstance;
        }
    
        public void GetRandomDocument()
        {
    
           Query query1 = db.Collection("Sports").WhereGreaterThanOrEqualTo(FieldPath.DocumentId, db.Collection("Sports").Document().Id).Limit(1);
           Query query2 = db.Collection("Sports").WhereLessThan(FieldPath.DocumentId, db.Collection("Sports").Document().Id).Limit(1);
    
            query1.GetSnapshotAsync().ContinueWithOnMainThread((querySnapshotTask1) =>
            {
    
                 if(querySnapshotTask1.Result.Count > 0)
                 {
                     foreach (DocumentSnapshot documentSnapshot in querySnapshotTask1.Result.Documents)
                     {
                         Debug.Log("Random ID: "+documentSnapshot.Id);
                     }
                 } else
                 {
                    query2.GetSnapshotAsync().ContinueWithOnMainThread((querySnapshotTask2) =>
                    {
    
                        foreach (DocumentSnapshot documentSnapshot in querySnapshotTask2.Result.Documents)
                        {
                            Debug.Log("Random ID: " + documentSnapshot.Id);
                        }
    
                    });
                 }
            });
        }
    

    如果学生有身份证号码,难道不可能使用随机生成的号码来选择哪个学生吗?@Geshode我将学生身份证指定为idSo文档,不可能使用随机生成的号码吗?这只是一个想法。你能解释一下你的想法吗?该问题重新打开,因为它与其他问题重复er语言。它没有内存效率。如果我只需要10个文档,为什么它可以检索1000个。使用第一种解决方案,它可以用于小数据集,但第二种方法对于10个随机学生只意味着11次读取。
    randomNumber
    在for循环中将是相同的,所以我认为相同的文档将被存储10次。@PratikButani很好地抓住了Pratik。刚刚用正确的方法更新了我的答案,感谢你帮助我更正答案。现在没有重复;)也从侧面完成了,因为最终你的答案给了我提示。:)谢谢。视频模型课看起来怎么样?这就是重点。。。从集合中获取所有文档非常昂贵而且效率低下!
    FieldValue.arrayUnion("yourArrayProperty")
    
    FieldValue.arrayRemove("yourArrayProperty")
    
        FirebaseFirestore database = FirebaseFirestore.getInstance();
        CollectionReference collection = database.collection(VIDEO_PATH);
        collection.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    List<VideoModel> videoModelList = new ArrayList<>();
                    for (DocumentSnapshot document : Objects.requireNonNull(task.getResult())) {
                        VideoModel student = document.toObject(VideoModel.class);
                        videoModelList.add(student);
                    }
    
                    /* Get Size of Total Items */
                    int size = videoModelList.size();
                    /* Random Array List */
                    ArrayList<VideoModel> randomVideoModels = new ArrayList<>();
                    /* for-loop: It will loop all the data if you want 
                     * RANDOM + UNIQUE data.
                     * */
                    for (int i = 0; i < size; i++) {
                        // Getting random number (inside loop just because every time we'll generate new number)
                        int randomNumber = new Random().nextInt(size);
    
                        VideoModel model = videoModelList.get(randomNumber);
    
                        // Check with current items whether its same or not
                        // It will helpful when you want to show related items excepting current item
                        if (!model.getTitle().equals(mTitle)) {
                            // Check whether current list is contains same item.
                            // May random number get similar again then its happens
                            if (!randomVideoModels.contains(model))
                                randomVideoModels.add(model);
    
                            // How many random items you want 
                            // I want 6 items so It will break loop if size will be 6.
                            if (randomVideoModels.size() == 6) break;
                        }
                    }
    
                    // Bind adapter
                    if (randomVideoModels.size() > 0) {
                        adapter = new RelatedVideoAdapter(VideoPlayerActivity.this, randomVideoModels, VideoPlayerActivity.this);
                        binding.recyclerView.setAdapter(adapter);
                    }
                } else {
                    Log.d("TAG", "Error getting documents: ", task.getException());
                }
            }
        });
    
        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    
            View view = inflater.inflate(R.layout.fragment_category_selection, container, false);
    
            btnNavFragCat1 = view.findViewById(R.id.btn_category_1);
    
            btnNavFragCat1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
    
                    questionKeyRef.document(tvCat1).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                        @Override
                        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                            if (task.isSuccessful()) {
    
                                DocumentSnapshot document = task.getResult();
                                List<String> questions = (List<String>) document.get("questions"); // This gets the array list from Firestore
    
                                List<String> randomList = getRandomElement(questions, 0);
    
                                removeDuplicates(randomList);
    
                                ...
                            }
                        }
                    });
    
                }
            });
    
            ...
    
            return view;
        }
    
        private List<String> getRandomElement(List<String> list, int totalItems) {
            int PICK_RANDOM_STRING = 3;
            Random rand = new Random();
            List<String> newList = new ArrayList<>();
            int count = 0;
            while (count < PICK_RANDOM_STRING) {
    
                int randomIndex = rand.nextInt(list.size());
                String currentValue = list.get(randomIndex);
                if (!newList.contains(currentValue)) {
                    newList.add(currentValue);
                    count++;
                }
            }
    
            return newList;
        }
    
        private void removeDuplicates(List<String> list) {
            try {
                Log.e("One", list.get(0));
                Log.e("Two", list.get(1));
                Log.e("Three", list.get(2));
    
                query1 = list.get(0); // In this vars are the strings stored with them you can then make a normal query in Firestore to get the actual document
                query2 = list.get(1);
                query3 = list.get(2);
            } catch (Exception e) {
                e.printStackTrace();
            }
    
        }
    
    FirebaseFirestore db;
    
        void Start()
        {
            db = FirebaseFirestore.DefaultInstance;
        }
    
        public void GetRandomDocument()
        {
    
           Query query1 = db.Collection("Sports").WhereGreaterThanOrEqualTo(FieldPath.DocumentId, db.Collection("Sports").Document().Id).Limit(1);
           Query query2 = db.Collection("Sports").WhereLessThan(FieldPath.DocumentId, db.Collection("Sports").Document().Id).Limit(1);
    
            query1.GetSnapshotAsync().ContinueWithOnMainThread((querySnapshotTask1) =>
            {
    
                 if(querySnapshotTask1.Result.Count > 0)
                 {
                     foreach (DocumentSnapshot documentSnapshot in querySnapshotTask1.Result.Documents)
                     {
                         Debug.Log("Random ID: "+documentSnapshot.Id);
                     }
                 } else
                 {
                    query2.GetSnapshotAsync().ContinueWithOnMainThread((querySnapshotTask2) =>
                    {
    
                        foreach (DocumentSnapshot documentSnapshot in querySnapshotTask2.Result.Documents)
                        {
                            Debug.Log("Random ID: " + documentSnapshot.Id);
                        }
    
                    });
                 }
            });
        }