I'm trying to check if the user's email is existing in my Firebase Realtime Database. I used Firebase Authenticate to get user's Google Play Email, and if the user's email is not existing on my Firebase, the user will be prompted to another activity. Here's my code:
MainActivity.class
// Let's declare Firebase
private DatabaseReference mDatabase;
private FirebaseAuth mAuth;
private FirebaseUser mUser;
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mUser = mAuth.getInstance().getCurrentUser();
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String dEmail = dataSnapshot.getValue().toString();
String gEmail = mUser.getEmail();
for(DataSnapshot data: dataSnapshot.getChildren()){
if(data.child("email").child(EncodeString(gEmail)).exists()) {
Toast.makeText(getApplicationContext(), "There's one: " + EncodeString(gEmail), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "No email: " + EncodeString(gEmail), Toast.LENGTH_LONG).show();
}
}
/*
if(dEmail == gEmail) {
startActivity(new Intent(getApplicationContext(), RegisterActivity.class));
finish();
} else {
Toast.makeText(getApplicationContext(), "No email", Toast.LENGTH_LONG).show();
}*/
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
public static String EncodeString(String string) {
return string.replace(".", ",");
}
public static String DecodeString(String string) {
return string.replace(",", ".");
}
Here's the structure of my Firebase Realtime Database
UPDATE: The question is how can I check if the email (the email is the one in my google play which is sholomon12#g..) is exisiting in my database. Note: I got the same email inserted, I just replaced the one in database with comma since I can't insert dot in firebase database
There is a workaround here when creating users in a Firebase database. Instead of using that random generated id provided by the push() method, use the email address. Your database structure should look like this:
Firebase-root
|
--- users
|
--- john#email,com
|
--- //user details
Now to check the users for existens, you can use exists() method on DatabaseReference object. So to chieve this, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference yourRef = rootRef.child("users").child("john#email,com");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
//do something
} else {
//do something else
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
yourRef.addListenerForSingleValueEvent(eventListener);
Related
I'm trying to check if the logged in user id matches the current user id to validate the user type.
I'm using the exists() method but doesn't seem to work. see code:
private String userID = FirebaseAuth.getInstance().getCurrentUser().getUid();
private DatabaseReference database = FirebaseDatabase.getInstance().getReference().child("basenode");
database.child("sand").child("administratorCountry").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(userID).exists()) {
System.out.println("THIS IS THE OUTPUT: "+ "TRUE");
}else{
System.out.println("THIS IS THE OUTPUT: "+ "FALSE");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
See Firebase structure:
I would appreciate any help! Thanks!
UPDATED
Data inside each user ID:
I'd suggest attaching a listener directly to the userID node and then checking that the returned data exists:
private String userID = FirebaseAuth.getInstance().getCurrentUser().getUid();
private DatabaseReference database = FirebaseDatabase.getInstance().getReference();
database.child("sand")
.child("administratorCountry")
.child(userID) // Create a reference to the child node directly
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This callback will fire even if the node doesn't exist, so now check for existence
if (dataSnapshot.exists()) {
System.out.println("The node exists.");
} else {
System.out.println("The node does not exist.");
}
}
#Override
public void onCancelled(DatabaseError databaseError) { }
});
You don't need to specify child("basenode"), as the getReference() method points directly to the root of your database, so you can remove child("basenode") from the database variable.
I'm creating an application with which the student will scan the QR code of a class created by a teacher.
After the student scans it, her/his details will store in the class list data. My problem is when I try to change the first name, middle name, and last name, only the first box is updating, while the 2nd and 3rd box are not.
Can someone here please help me?
Here's the code that updates the first box:
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String uid = user.getUid();
ref = FirebaseDatabase.getInstance().getReference();
ref.child("users").child("student").child(uid).addListenerForSingleValueEvent(new ValueEventListener() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String uid = user.getUid();
String newFirstName = oldEmail.getText().toString().trim();
String newMiddleName = middlename.getText().toString().trim();
String newLastName = lastname.getText().toString().trim();
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
ref.child("users").child("student").child(uid).child("firstname").setValue(newFirstName);
ref.child("users").child("student").child(uid).child("middlename").setValue(newMiddleName);
ref.child("users").child("student").child(uid).child("lastname").setValue(newLastName);
progressBar.setVisibility(View.GONE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(AccountSettingsActivity.this, "Failed to update name!", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
});
Here's the code that updates the second and third boxes:
ref.child("users").child("teacher").child("class").child("Listofstudents").child(user.getUid().toString().trim()).addListenerForSingleValueEvent(new ValueEventListener() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String uid = user.getUid();
String newFirstName = oldEmail.getText().toString().trim();
String newMiddleName = middlename.getText().toString().trim();
String newLastName = lastname.getText().toString().trim();
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
ref.child("users").child("teacher").child(ref.child("teacher").getKey()).child("class").child(ref.child("class").getKey()).child("Listofstudents").child(user.getUid().toString().trim()).child("firstname").setValue(newFirstName);
ref.child("users").child("teacher").child(ref.child("teacher").getKey()).child("class").child(ref.child("class").getKey()).child("Listofstudents").child(user.getUid().toString().trim()).child("middlename").setValue(newMiddleName);
ref.child("users").child("teacher").child(ref.child("teacher").getKey()).child("class").child(ref.child("class").getKey()).child("Listofstudents").child(user.getUid().toString().trim()).child("lastname").setValue(newLastName);
// TODO: handle the case where the data already exists
}
else {
// TODO: handle the case where the data does not yet exist
}
}
#Override
public void onCancelled(DatabaseError firebaseError) {
Toast.makeText(AccountSettingsActivity.this, "Failed to update name!", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
});
You don't need to add a listener in order to make an update in a Firebase database.
Please see my answer at this post.
Hope it helps.
How to only retrieve email addresses inside the key, not all the items. I have an items Name and Email, but I only want to retrieve EMAIL.
example:
Email: HOTMAIL
Email: GMAIL
first make database reference as
mReference= FirebaseDatabase.getInstance().getReferenceFromUrl(FIREBASE_URL_USERS);
here FREBASE_URL_USERS is a url of users key you can get it from firebase console.
it is a combination of your unique_fiirebase_root_url / User01
then get snapshot of data as
mDatabseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
dataSnapshot.getValue("Email");
// use log to check whetehr you are getting email or not
#Override
public void onCancelled(DatabaseError databaseError) {
// log error and do something
}
});
Assuming that the user emails are unique, you can query the users records by its email value as follows:
final String email = "hani.mehdi#email.com";
ValueEventListener onFindListener = new ValueEventListener() {
#Override
public void onCancelled(DatabaseError error) {
Log.e(TAG, error.getMessage());
}
#Override
public void onDataChange(DataSnapshot snapshot) {
Map<String, User> result = snapshot.getValue(Map.class);
if (result.contains(email) {
User user = result.get(email);
Log.i(TAG, user.toString());
} else {
Log.d(TAG, "Not found: " + email);
}
}
};
DatabaseReference userReference = database.getReference("users")
.orderByChild("email")
.equalTo(email)
.addListenerForSingleValueEvent(onFindListener);
Currently I create a Listing object and store a bunch of fields in there. Two of the fields I need to store are the current User's email and name. I am trying to get those two fields as follows
dbRef = database.getReference().child("Users").child(emailKey);
dbRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserInfo userIn = dataSnapshot.getValue(UserInfo.class);
email1 = userIn.email;
sellerName = userIn.username;
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
After this bit of code I have the line
DatabaseReference temp = dbRefL.push();
temp.setValue(l);
All of this code is called by me pressing a button. The first time I press the button, the entire Listing object is pushed to Firebase just the way I want it EXCEPT the user email and username aren't there because they're blank. The second time I press the button the Strings are there how I want.
My guess is that this is because OnDataChange only executes after I push the Listing object. Is this true? How can I get OnDataChange to execute before I push the listing object?
The listener onDataChange() callbacks are asynchronous. The reason that your email and username is blank is because onDataChange hasn't been executed yet to make sure you push data after email and username are retrieve, put the code inside onDataChange()
dbRef = database.getReference().child("Users").child(emailKey);
dbRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserInfo userIn = dataSnapshot.getValue(UserInfo.class);
email1 = userIn.email;
sellerName = userIn.username;
//set up your l value
DatabaseReference temp = dbRefL.push();
temp.setValue(l);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Once you press the button above code should be called to obtain email and username then push the data as you want.
User addValueEvenListener like :
DatabaseReference map = database.getReference("field_name");
map.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String data = (String) dataSnapshot.getValue();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
****OR using****
database.getReference("field_name").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.e(TAG, "Field data", dataSnapshot.getValue(String.class));
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Failed to read value
Log.e(TAG, "Failed to read user", databaseError.toException());
}
});
I have a ValueEventListener, and the inner code is never being reached. My app is authenticating, but I can't retrieve data and I'm not sure what I'm missing. In the code below, when I check, uid has the correct value, and the data path ("Users/[uid]") is correct, but none of the inner code in the value event listener is never being reached. I've also tried to place a listener right at the root, with the same result.
I've set up Firebase using the menu options, adding both Authentication and Realtime Database to my app; authentication is working fine, so I'm wondering if there is something else that needs to be configured for the realtime database? I've read the documentation and walked through many examples but I can't see anything I'm missing.
uid = FirebaseAuth.getInstance().getCurrentUser().getUid().toString();
DatabaseReference userRef = ref.child("Users").child(uid).getRef();
ValueEventListener userListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
if (user == null) {
SettingsLoad();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e("User", "User not found" );
}
};
userRef.addListenerForSingleValueEvent(userListener);
Try this!
I've just added else condition and log or toast the results!!
uid = FirebaseAuth.getInstance().getCurrentUser().getUid().toString();
DatabaseReference userRef = ref.child("Users").child(uid).getRef();
ValueEventListener userListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
if (user == null) {
SettingsLoad();
}
**else {
Log.d("tag","User Found!");
}**
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e("User", "User not found" );
}
};
userRef.addListenerForSingleValueEvent(userListener);