2

I have string variable named customerId that is initialized to be empty until my getCustomerID method should populate it. But the datasnapshot for some reason is not populating it. Here is the how the string is initialized below

private String customerID = " ";

Here is the method below

public void getAssignedCustomer() {
        String driverId = FirebaseAuth.getInstance().getCurrentUser().getUid();
        DatabaseReference assignedCustomerRef =FirebaseDatabase.getInstance().getReference().child("Users").child("Drivers").child(driverId).child("customerRideId");
        assignedCustomerRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if(dataSnapshot.exists()){
                        customerID= dataSnapshot.getValue().toString();
                        getAssignedCustomerLocation();

                }

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });


    }

The datasnapshot should populate the string variable because there is an acdtual value in it. Below is how a snippet of my firebasedatabase

"sfdqfkoxYjXB2YRDTfIaezWgkBd2":{  
            "customerRideId":"pUa4kMRMFIMEqZFYQ31w9eOpVhB3"
         },

As you cacn see customerRideId actually has a value in it

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

1 Answers1

0

Here's the problem:

Your getAssignedCustomer() method cannot populate your customerId variable immediately.

This is because addValueEventListener(...) is asynchronous (meaning). A quick solution to your problem would be to get the value first before doing anything else. To fix this, you can use AsyncTask.

I hope this helps.. Merry coding!

Taslim Oseni
  • 6,086
  • 10
  • 44
  • 69
  • I created an interface and made getAssignedCustomer a call back method. But what I cant figure out how to get the string from the server and put it in a separate variable named cutomerId if im using call back. I need to store that string in a variable and so I can send that string to another method that I will need later – Timothy Smith Sep 16 '19 at 01:18
  • Yeah, I understand you, Timothy. You can also add a method to your interface that would simply set the value gotten from `geetAssignedCustomer()` and set it to a global variable. Let me know if you face any difficulty. – Taslim Oseni Sep 16 '19 at 11:22
  • I dont think it is possible to make a variable that is already classified as a string Global. I need the variable to be a string in order to save the value from the server. – Timothy Smith Sep 21 '19 at 16:00
  • Why not? Simply declare your global string and set a value to it. – Taslim Oseni Sep 21 '19 at 19:17