Check firebase database data is retrieved [duplicate] - java

This question already has an answer here:
Determining if Firebase didn't download data with startAt and endAT
(1 answer)
Closed 4 years ago.
I wanna know if Firebase data is retrieved.
For example:
database.child("name").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String name = dataSnapshot.getValue().toString();
//if(data.isdownloaded){Send data to another fragment via bundle}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Is there any complete listener for this?

you can add a if statement inside the onDataChange() if you data is retrieved that true will be pass to if as code below
database.child("name").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChildren()) // add this if statement
{
............ rest of the code
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Hope this is helping

Related

Firebase-Android function should work but isn't [duplicate]

This question already has answers here:
How to return DataSnapshot value as a result of a method?
(6 answers)
getContactsFromFirebase() method return an empty list
(1 answer)
Closed 7 months ago.
For some reason, the following function always returns 0. Does someone know why?
public int GetOnlineFriendsNum(){
OnlineFriendsCounter = 0;
database.getReference().child("users").child(mAuth.getCurrentUser().getPhoneNumber()).child("Friends").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot snap : snapshot.getChildren()) {
String friend = snap.getValue().toString();
database.getReference().child("users").child(friend).child("IsHome").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapboolean) {
if((boolean)snapboolean.getValue()){
OnlineFriendsCounter++;
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
});
return OnlineFriendsCounter;
}
I added a firebase tree image^^
No need for another value change event,
You can convert it to your model directly or parse using map.
for (DataSnapshot snap : snapshot.getChildren()) {
HasMap<String,Object> friends = snap.getValue();
for (String mobileNumber : friends .keySet())
{
HasMap<Strin,Object> friend = friends.get(mobileNumber);
if(friend.get("IsHome").toString().equals("true"))
{
OnlineFriendsCounter++;
}
}
}

Unable to set an ArrayList's value when populated from a database

ccontacts = new ArrayList<>();
DatabaseReference dbGelenler = db.getReference("Filmler");
dbGelenler.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot gelenler:dataSnapshot.getChildren()){
ccontacts.add(new Data(gelenler.getValue(Film.class).getAciklama(),gelenler.getValue(Film.class).getBen(),gelenler.getValue(Film.class).getImdb(),gelenler.getValue(Film.class).getIsim(),gelenler.getValue(Film.class).getIzlemeLinki(),gelenler.getValue(Film.class).getKategori(),gelenler.getValue(Film.class).getNe(),gelenler.getValue(Film.class).getService(),gelenler.getValue(Film.class).getTrailer(),gelenler.getValue(Film.class).getUrl(),gelenler.getValue(Film.class).getWhat(),gelenler.getValue(Film.class).getYear()));
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
for (Data d:ccontacts){
b.setText(d.getIsim());
}
When I directly set the text via gelenler.getValue() it works, however when I want to populate an ArrayList with this information it fails and receives null. Any help would be appreciated.

Retrieve Firebase data from some object based on data provided by some object

I am new to Android Firebase.I have some app in which I have saved id's of all hotels in one object. I have only id's there so based on those id's I want to retrieve all information which is inside some other object.
What i have tried so far
reference=FirebaseDatabase.getInstance().getReference().child(getResources().getString(R.string.all_countries)).child(country).child(city).child("Hotel");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
hotels=new ArrayList<>();
for (DataSnapshot dataSnapshot1:dataSnapshot.getChildren()){
String id=dataSnapshot1.getKey();
hotelIDs.add(id);
reference1=FirebaseDatabase.getInstance().getReference().child("Hotel").child(id);
reference1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Hotel hotel=dataSnapshot.getValue(Hotel.class);
hotels.add(hotel);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
// }
hotelsAdapter=new HotelsAdapterUser(hotels,UserViewHotels.this,"Hotel");
hotelsRV.setAdapter(hotelsAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.e("iamhere",databaseError.getMessage());
}
});
I have all id's in hotelIDs array list and based on that when i try to get data my adapter is calling before the hotels array list is set up which means i am getting no data.Please help
The easiest fix is to simply notify the adapter each time that you add a hotel to the list:
reference1.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Hotel hotel=dataSnapshot.getValue(Hotel.class);
hotels.add(hotel);
adapter.notifyDataSetChanged()
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
I made a few more changes here:
Use addListenerForSingleValueEvent, so that we don't keep the listener attached. With your original code, if you made a change to the hotel in the database, a second copy of that hotel would be added to the list.
Don't leave onCancelled empty, as you may be hiding important error messages there. I implemented it in the simplest way possible here.

How to check if a value exists in firebase [duplicate]

This question already has answers here:
How to return DataSnapshot value as a result of a method?
(6 answers)
Closed 4 years ago.
before reading I'm a newbie trying to learn android development so don't go hard on me, please.
I have this Realtime database firebase :
I'm trying to check if the entered email exists , i've tried a method but it did not work out for me.
I tried this method :
private boolean checkIfExistes() {
reference.child("Users").orderByChild("email").equalTo(Email.getText().toString()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
CheckExists =true;
else
CheckExists =false;
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
if (CheckExists)
return true;
else
return false;
}
it always returns false though even if the email exists. Help please.
Try this:
boolean CheckExists =false; //declare and assign default value in global scope
reference.child("Users").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> userChildren = dataSnapshot.getChildren();
for (DataSnapshot user: userChildren) {
User u = user.getValue(User.class); //make a model User with necessary fields
if(u.email.equalsIgnoreCase(Email.getText().toString())){
CheckExists =true;
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
private DatabaseReference rootRef,userRef;
get the initialize firebase in oncreare method
rootRef = FirebaseDatabase.getInstance().getReference();
userRef = rootRef.child("Users");
here the code for checking email exist or not
userRef.orderByChild("email").equalTo(emailEdt.getText().toString())
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
hideProgress();
if (dataSnapshot.exists()){
Toast.makeText(LoginActivity.this,"User already exists",Toast.LENGTH_SHORT).show();
}else {
UserLogin user = new UserLogin(emailEdt.getText().toString(),profilePath);
DatabaseReference db = userRef.push();
db.setValue(user);
//Log.d(TAG,"user key is::: "+db.getKey());
prefs.savEmail(emailEdt.getText().toString());
prefs.savProfileUrl(profilePath);
prefs.savKey(db.getKey());
openMainActivity();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
hideProgress();
Toast.makeText(LoginActivity.this,databaseError.getMessage(),Toast.LENGTH_SHORT).show();
}
});

Problem retrieve similar child element of firebase

I want to retrieve only the date and all the date element at once and store them in array in the firebase as shown below.
i have used the following code to retrieve but failed to that.
public void showData(View view) {
final ArrayList<String> date = new ArrayList<>();
firebaseDatabase = FirebaseDatabase.getInstance().getReference().child("Date");
firebaseDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
date.add(dataSnapshot.getValue().toString());
display.setText(dataSnapshot.getValue().toString());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
Please help to find a solution for this.
The firebase reference is wrong, you should go from the top node to the date node.
Change this:
firebaseDatabase = FirebaseDatabase.getInstance().getReference().child("Date");
into this:
firebaseDatabase = FirebaseDatabase.getInstance().getReference().child("Name");
firebaseDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
date.add(datas.child("Date").getValue().toString());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Since you want to get all Date then put the firebase reference at the node Name and loop inside the names to be able to retrieve all the dates.
If you want to get the date of one user example Ravi, then you do not need to loop, you can do the following:
firebaseDatabase = FirebaseDatabase.getInstance().getReference().child("Name").child("Ravi").child("Date");
firebaseDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
date.add(dataSnapshot.getValue().toString());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
As said by #PeterHaddad in the previous answer, the sequence to access the data you have taken is not right. You may try this way, if nothing else helped until yet.
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
rootRef.child("Names").orderByChild("Date").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds: dataSnapshot.getChildren()){
date.add(ds.getValue(String.class));
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
//Also as you've told that code is not working, please tell, what exactly is not working

Categories

Resources