0

I am trying to get last created document id to help me with create a collection in the same place

for that i created id_helper field just for that, When getLastCreatedDocumentID() executed always it return 0 so newId always taking 1 value ,but after executed the next line OnSuccessListener or OnCompleteListener method that in getLastCreatedDocumentID() Be fired!!

How to solve it?

final String ID_HELPER = "id_helper";
int id;

public int getLastCreatedDocumentID() {

    id = 0;
    Query getLastID =
            db.collection(UNIVERSITY_COLLECTION).whereGreaterThan(ID_HELPER, 0)
                    .orderBy(ID_HELPER, Query.Direction.DESCENDING).limit(1);
    getLastID.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
        @Override
        public void onSuccess(QuerySnapshot documentSnapshots) {
        id=Integer.parseInt(documentSnapshots.getDocuments().get(0).get(ID_HELPER).toString());
        }
    });

    /*
    .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (task.isSuccessful() && task.getResult().size() == 1) {
                id = Integer.parseInt(task.getResult().getDocuments().get(0).get(ID_HELPER).toString());
            }
        }
    });
     */
    return id;
}
public void onClickbtn(View view) {
    // ********* University Collection **************
    int newId=getLastCreatedDocumentID()+1;
    University item_u = new University
            (newId, "", "", "", new GeoPoint(0, 0));
    db.collection("university").add(item_u);



    // ********* Exam Collection **************
    final Exam item = new Exam();
    db.collection(UNIVERSITY_COLLECTION).whereEqualTo(ID_HELPER,newId).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            DocumentSnapshot doc = task.getResult().getDocuments().get(0);
            String doc_id = doc.getId();

            db.collection(UNIVERSITY_COLLECTION).document(doc_id).collection("exam").add(item);

}
Modgo
  • 77
  • 2
  • 8

0 Answers0