ArrayList <string>方法返回一个空数组,从firebase获取数据

时间:2018-12-04 16:36:59

标签: android firebase arraylist google-cloud-firestore

我的返回文件有问题。由于下载数据需要花费几秒钟的时间,因此当该方法返回ArrayList时,它仍然为空。实际上,如果我输入那行代码Log.v("array", String.valueOf(partecipantsArrayList)); 首先打印0,然后打印填充的数组。所以我必须等return语句之前..有没有办法实现这一目标?

public ArrayList<String> getPartecipantsList(){
    String email = getEmail();
    String groupTitle = getTitleBar();
    DocumentReference docRef = db.collection("users").document(email).collection("Group").document(groupTitle);

    docRef.get()
            .addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                @Override
                public void onComplete(@NonNull Task<DocumentSnapshot> task) {


                        DocumentSnapshot document = task.getResult();


                        //Extracting participants ArrayList from the document
                        for(Object item : task.getResult().getData().values()) {

                            String[] values = String.valueOf(item).replace("[", "").replace("]", "").split(",");

                            for (String value : values){

                                    partecipantsArrayList.add(value);

                            }

                        }
                        partecipantsArrayList.remove(String.valueOf("["));
                        partecipantsArrayList.remove(partecipantsArrayList.size() - 1);
                        Log.v("array", String.valueOf(partecipantsArrayList));

                    }

                })

            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {

                }
            });


    return partecipantsArrayList;
}

1 个答案:

答案 0 :(得分:1)

这是异步任务,您可以按如下所示调整此代码。

将该方法的签名更改为return void

public void getPartecipantsList();

完成后执行下一个动作

                @Override
                public void onComplete(@NonNull Task<DocumentSnapshot> task) {

                        ...............
                        partecipantsArrayList.remove(String.valueOf("["));
                        partecipantsArrayList.remove(partecipantsArrayList.size() - 1);

                        Log.v("array", String.valueOf(partecipantsArrayList));
                       // do your action by calling next method from here
                      //eg: setResultFromArray(partecipantsArrayList);
                    }

onFailure发生故障时执行失败操作或调用方法。

                @Override
                public void onFailure(@NonNull Exception e) {
                     //......
                }