0

Is this script wrong, because the data I receive is null while I've added data on the Cloud Firestore. I do not use RecyclerView because I only need one data only.

This is the script:

private void getCustomer(){
        firestoreDB.collection("customer")
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            customers = new ArrayList<>();
                            for (DocumentSnapshot doc : task.getResult()) {
                                Customer customer = doc.toObject(Customer.class);
                                customer.setId_customer(doc.getId());
                                customers.add(customer);
                            }
                        } else {
//                            Log.d(TAG, "Error getting documents: ", task.getException());
                        }
                    }
                });

        firestoreListener = firestoreDB.collection("customer")
                .addSnapshotListener(new EventListener<QuerySnapshot>() {
                    @Override
                    public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
                        if (e != null) {
//                            Log.e(TAG, "Listen failed!", e);
                            return;
                        }
                        customers = new ArrayList<>();
                        for (DocumentSnapshot doc : documentSnapshots) {
                            Customer customer = doc.toObject(Customer.class);
                            customer.setId_customer(doc.getId());
                            customers.add(customer);
                        }
                    }
                });

        id_customer = customers.get(0).getId_customer();
    }

and this is my firestore:

my firestore

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
RPH
  • 15
  • 5

1 Answers1

0

You cannot use something now that hasn't been loaded yet. With other words, you cannot simply use the following line of code:

id_customer = customers.get(0).getId_customer();

Outside the onSuccess() method because it will always be null due the asynchronous behaviour of this method. This means that by the time you are trying to use the id_customer variable outside that method, the data hasn't finished loading yet from the database and that's why is not accessible.

A quick solve for this problem would be to use that result only inside the onSuccess() method, or if you want to use it outside, I recommend you see the last part of my anwser from this post in which I have exaplined how it can be done using a custom callback. You can also take a look at this video for a better understanding.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193