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

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();
}
});

Related

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 and update child data in firebase

I have a problem with retrieving and updating a value from Firebase realtime database:
reff = FirebaseDatabase.getInstance().getReference("Items").child(a);
reff.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snap : dataSnapshot.getChildren()) {
Items items = dataSnapshot.getValue(Items.class);
Integer na = items.getItemQuantity();
if (na <= 0) {
Toast.makeText(CheckOut.this, "Out of Stock", Toast.LENGTH_LONG).show();
} else {
na--;
snap.child("itemQuantity").getRef().setValue(na);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Error log on line 60 from the if-else.
According to your last comment:
yes a is the barcode that i will receive from barcode. itemQuantity of a single child.
To get the value of itemQuantity property of a single child, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference barcodeRef = rootRef.child("Items").child("1234567781");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
long itemQuantity = dataSnapshot.child("itemQuantity").getValue(Long.class);
Log.d(TAG, String.valueOf(itemQuantity));
//Do what you need to do with itemQuantity
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
barcodeRef.addListenerForSingleValueEvent(valueEventListener);
The result in the logcat will be:
14
The problem in your code is that you are looping through the dataSnapshot object using getChildren() method when is actually not necessary. You should only get the correct reference as in the above code and simply use the value of itemQuantity property as needed.

How do I pass data out of the onDataChange method? [duplicate]

This question already has an answer here:
getContactsFromFirebase() method return an empty list
(1 answer)
Closed 4 years ago.
I have a boolean set up to check for duplicate usernames in an app. I want the boolean to return data based on the result of an onDataChange in a ValueEventListener. Here's what I have:
private boolean isUsernameValid(final String username) {
mReference = FirebaseDatabase.getInstance().getReference();
Query query = mReference.child("users").child(username);
ValueEventListener mListener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
//create condition that would make isUsernameValid return false
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
mReference.addListenerForSingleValueEvent(mListener);
return //if that condition is not met;
}
If you try to do something like this, you will always be returning false, since Firebase is asynchronous, you will need to wait a little bit depending on your connection in order to return any value from dataSnapshot()
private boolean isUsernameValid(final String username) {
boolean isUsernameValid;
mReference = FirebaseDatabase.getInstance().getReference();
Query query = mReference.child("users").child(username);
ValueEventListener mListener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
//create condition that would make isUsernameValid return false
isUsernameValid = true;
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
mReference.addListenerForSingleValueEvent(mListener);
return isUsernameValid //if that condition is not met;
}
To solve this issue you can create an interface that will fires right when we know we have the results from onDataChange() and then you can return anything from there
first create an interface
public interface FirebaseSuccessListener {
void onDataFound(boolean isDataFetched);
}
Then we just do your method that checks for the user if exists
private void isUsernameValid(final String username, FirebaseSuccessListener dataFetched) {
mReference = FirebaseDatabase.getInstance().getReference();
Query query = mReference.child("users").child(username);
ValueEventListener mListener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
//here we are telling to our interface that the data has been found and then we can do anything with it outside this method
dataFetched.onDataFound(true);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
mReference.addListenerForSingleValueEvent(mListener);
}
And then we can call the method in order to get your value from inside onDataChange()
isUsernameValid.(new FirebaseSuccessListener() {
#Override
public void onCallback(boolean isDataFetched) {
if(isDataFetched){
//you know the value is true, here you can update or request any change for example you can do this
userIsOnFirebase(true);
}else{
userIsOnFirebase(false);
}
}
});
private boolean userIsOnFirebase(boolean isOnFirebase){
return isOnFirebase;
}
then use this method above to return if the user is or not in your db. Make sure when you call userIsOnFirebase since it will return false if the data is still not fetched

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

Check firebase database data is retrieved [duplicate]

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

Categories

Resources