Firestore collection.get()完成操作后返回值

时间:2018-05-08 16:51:03

标签: android firebase google-cloud-firestore

我正在运行与this question中的问题类似的代码,除了,我从每个文档中获取数组并将其元素添加到全局ArrayList中。之后,在collection.get()之外,我对该数组执行操作并返回。但是,如果我在onSuccess侦听器中记录全局ArrayList大小,它会给出正确答案,但如果我在collection.get()之外这样做,它总是给出0.我的问题是我无法从内部返回onSuccess因为这不会返回我的整个函数所以我需要在没有填充ArrayList的collection.get()之后执行它,大概是因为get()操作返回Task<>这是一个< strong>异步操作,因此它不会等待它完成。这是我的代码:

public static boolean Validator(final String sometext) {
    FirebaseFirestore db = FirebaseFirestore.getInstance();

    final ArrayList<String> mArrayList = new ArrayList<>();

    db.collection("my_collection").get()
        .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
            @Override
            public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                if (queryDocumentSnapshots.isEmpty()) {
                    Log.d(TAG, "Validator onSuccess: LIST EMPTY");
                    return;
                } else {

                    // Convert the Query Snapshot to a list of Document Snapshots, in this
                    // case, one document for each my_collection
                    List<DocumentSnapshot> my_collections = queryDocumentSnapshots.getDocuments();


                    for (int i = 0; i < my_collections.size(); i++) {
                        ArrayList<String> mArrayitems = (ArrayList<String>) my_collections.get(i).get("array");

                        for (int j = 0; j < mArrayitems.size(); j++) {
                            Log.d(TAG, "Adding array: " + mArrayitems.get(j).toString());
                            mArrayList.add(mArrayitems.get(j).toString());
                        }
                    }
                    Log.d(TAG, "Validator onSuccess: array list built");
                }
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.d(TAG, "Validator onFailure: " + e);
            }
        });

  // check if the given sometext matches a array in the list
  Log.d(TAG, "array list size: " + mArrayList.size());
  if (mArrayList.size() > 0) {
    for (int i = 0; i < mArrayList.size(); i++) {
        if (sometext.endsWith(mArrayList.get(i))) {
            return true
        }
      }
   }
   return false;
 }

修改
我试图通过一个看起来像这样的回调来做到这一点:

// constructor
public Validator(String sometext) {
    this.valid = false;
    this.sometext = sometext
}

public interface myCallback{
    void onCallback(boolean valid);
}

public boolean validate() {

  readData(new MyCallback() {
        @Override
        public void onCallback(boolean valid) {
            setValid(valid);
        }
    });
  return this.valid;
 }

private void readData(final MyCallback myCallback) {
    FirebaseFirestore db = FirebaseFirestore.getInstance();

    db.collection("my_collection").get()
            .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                @Override
                public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                    if (queryDocumentSnapshots.isEmpty()) {
                        Log.d(TAG, "Validator onSuccess: LIST EMPTY");
                    } else {

                        List<DocumentSnapshot> my_collections = queryDocumentSnapshots.getDocuments();

                        ArrayList<String> mArrayList = new ArrayList<>();

                        for (int i = 0; i < my_collections.size(); i++) {
                            ArrayList<String> mArrayItems = (ArrayList<String>) my_collections.get(i).get("array");
                            for (int j = 0; j < mArrayItems.size(); j++) {
                                Log.d(TAG, "Adding array: " + mArrayItems.get(j).toString());
                                mArrayList.add(mArrayItems.get(j).toString());
                            }
                        }

                        boolean result = false;

                        Log.d(TAG, "array list size: " + mArrayList.size());
                        if (mArrayList.size() > 0) {
                            for (int i = 0; i < mArrayList.size(); i++) {
                                if (sometext.endsWith(mArrayList.get(i))) {
                                    result = true;
                                    Log.d(TAG, "MATCH FOUND");
                                    break;
                                }
                            }
                        }

                        myCallback.onCallback(result);

                    }
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.d(TAG, "Validator onFailure: " + e);
                }
            });
}

我遇到的问题是在validate()中我想在回调完成后返回正确的有效值,因为它在回调完成之前当前返回了不正确的值。

1 个答案:

答案 0 :(得分:0)

我首先使用@AlexMamo的解决方案here解决了我的问题,然后使用此解决方案here监听正在更改的有效变量。

public class ValidatorVariable {
    private boolean valid;
    private ChangeListener listener;

    public boolean isValid(){
        return valid;
    }

    public void setValid(boolean valid){
        this.valid = valid;
        if (listener != null) listener.onChange();
    }

    public ChangeListener getListener(){
        return listener;
    }

    public void setListener(ChangeListener listener){
        this.listener = listener;
    }

    public interface ChangeListener {
        void onChange();
    }
}

用于:

ValidatorVariable vv = new ValidatorVariable();
        vv.setListener(new ValidatorVariable.ChangeListener() {
            @Override
            public void onChange() {
                if (vv.isValid()){
                    // do stuf
                }
            }
        });