Can I get the value without using event listeners in firebase on Android?

I am making an Android application using the new version of the Google Firebase Realtime database.

I get my data using ValueEventListener and ChildEventListener when data is changed / added / deleted / moved, etc.

Now I have a problem.

My details:

"user 1": { "name":"abc" } 

and I have a button called "getName".

I want to get the "name" value in user data 1 when I clicked the getName button.

  getName.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bla bla.. } }); 

Is it possible? Can I get value without using listeners?

Waiting for your help. thanks.

+5
source share
3 answers

Yes, you can do this using addListenerForSingleValueEvent . This will retrieve the value only once, unlike the ValueEventListener and ChildEventListener . So your code will look something like this

 getName.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ref.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { // do some stuff once } @Override public void onCancelled(FirebaseError firebaseError) { } }); 
+6
source

In fact, this will not change every time you change the data, and it will probably cause all your actions, which are pretty useless, I don’t even know why they did it ... waiste of time.

+6
source

Take a look at the Task API Structure :

 @Override public void onClick(View view) { getUser(); } private Task<User> getUser(String id) { final TaskCompletionSource<User> tcs = new TaskCompletionSource(); ref.child("users") .child(id) .addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onCancelled(FirebaseError error) { tcs.setException(error.toException()); } @Override public void onDataChange(DataSnapshot snapshot) { tcs.setResult(snapshot.getValue(User.class)); } }); return tcs.getTask(); } 
+1
source

All Articles