salRad
salRad

Reputation: 320

loading data from Firebase returns null only for the first time

I'm writing two values into firebase database as shown below

    String key = mClientDatabaseReference.push().getKey();

                   // get user input and set it to result
                   // edit text
                   Client client = new Client( firstNameEditText.getText().toString(), lastNameEditText.getText().toString() );
                   mClientDatabaseReference.child( key ).child( "firstName" ).setValue( firstNameEditText.getText().toString() );
                   mClientDatabaseReference.child( key ).child( "lastName" ).setValue( lastNameEditText.getText().toString() );

and everything is working fine except for a tiny annoying thing that is happening with the ChildEventListener. when the onChildAdded is called it is called after setting the value of the first name and it doesn't wait until the second name value is being sat, so I get only the first name with the second name being null and I have to reopen the activity to get the full firs and last name. this is the code in onChildAdded

 public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            Client client = dataSnapshot.getValue( Client.class );
            mClientAdapter.add( client );           
            Log.d(TAG+"Added",dataSnapshot.getValue(Client.class).toString());
        }

how can I get over this problem?

Upvotes: 2

Views: 1158

Answers (1)

Peter Haddad
Peter Haddad

Reputation: 80914

You can use addvalueeventlistener:

 DatabaseReference reference = FirebaseDatabase.getInstance().getReference("users");

reference.addValueEventListener(new ValueEventListener() {
   @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
    for(DataSnapshot datas: dataSnapshot.getChildren()){
   String name=datas.child("firstName").getValue().toString();
   String lname=datas.child("lastName").getValue().toString();
  }
}
    @Override 
public void onCancelled(DatabaseError databaseError) {
    }
 });

since you want to retrieve data only, then use addvalueeventlistener or addListenerForSingleValueEvent if you want to read once. Assuming you have the following database:

users
 userid
    firstName:firstname
    lastName: lastname

Upvotes: 1

Related Questions