This is pretty direct forward but I have a problem with multiple users.When the first user signs in,his name and email are fetched with no issues but when he signs out and another user signs in (same phone), current user details return null.
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
String uid = Objects.requireNonNull(firebaseAuth.getCurrentUser()).getUid();
userDetails = FirebaseDatabase.getInstance().getReference().child("Users").child(uid);
myref.keepSynced(true);
userDetails.keepSynced(true);
name = view.findViewById(R.id.my_name);
mail = view.findViewById(R.id.my_mail);
userDetails.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String Name = dataSnapshot.child("name").getValue().toString();
String Email = dataSnapshot.child("email").getValue().toString();
name.setText(Name);
mail.setText(Email);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Turns out the code is fine, only problem is my firebase structure. The first user "email" and "name" are in lowercase, the rest start with a capital letter users node, firebase Image
Related
I need to get the specific user data using the user email on the real time database. This is my code, This code running without errors but the data is not display in the interface.I think datasnapshot retrieving part is not correct. please help me to solve this.
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String userEmail = user.getEmail();
DatabaseReference rootReference = FirebaseDatabase.getInstance().getReference();
Query myUsersQuery = rootReference.child("Children").orderByChild("childrenParentEmail").equalTo(userEmail);
myUsersQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("Children").getValue(String.class);
childrenNameEdt.setText(name);
childrenBirthdayEdt.setText(dataSnapshot.child("childrenBirthday").getValue(String.class));
childrenParentNameEdt.setText(dataSnapshot.child("childrenParentName").getValue(String.class));
childrenParentAddressEdt.setText(dataSnapshot.child("childrenParentAddress").getValue(String.class));
childrenParentContactNumberEdt.setText(dataSnapshot.child("childrenParentContactNumber").getValue(String.class));
childrenParentEmailEdt.setText(dataSnapshot.child("childrenParentEmail").getValue(String.class));
childrenTransportTypeEdt.setText(dataSnapshot.child("childrenTransportType").getValue(String.class));
childrenTransportContactNumberEdt.setText(dataSnapshot.child("childrenTransportContactNumber").getValue(String.class));
//childrenID.setText(dataSnapshot.child("password").getValue(String.class));
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException();
}
});
When you execute a query against the Firebase Realtime Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.
Your code will need to handle that list, by looping over dataSnapshot.getChildren(). So something like:
myUsersQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren();
String name = snapshot.child("Children").getValue(String.class);
childrenNameEdt.setText(name);
...
How do i Check Check in Database with User Entered Phone Number?
And i Want Notice to the User If he already registered.
String _getUserEnteredPhoneNumber = pNumber.getEditText().getText().toString().trim();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("People");
Query checkUser = reference.orderByChild("uid").equalTo(_getUserEnteredPhoneNumber);
checkUser.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
pNumber.setError("Username Exists,Please Enter Another User Name");
} else {
updateData();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
If you want to query on the phone number, you need to specify that property in your call to orderByChild(). So:
Query checkUser = reference.orderByChild("phone").equalTo(_getUserEnteredPhoneNumber);
I highly recommend checking out the documentation on sorting and filtering data, which covers Firebase's query capabilities in more detail.
This question already has answers here:
Checking if a particular value exists in the Firebase database
(6 answers)
Closed 2 years ago.
In my app I have to verify that there are not more than two users with the same name. I tried it with the following code, but when it detects that the user who tries to register already exists, it appears a toast that indicates to change it.
The problem is that even if you know that name already exists and although the toast appears, the account is created without importing the imposed condition, thus creating two users with the same username.
How could I avoid that, that two users with the same name will be created?
regBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
regBtn.setVisibility(View.INVISIBLE);
loadingProgress.setVisibility(View.VISIBLE);
final String email = userEmail.getText().toString();
final String password = userPassword.getText().toString();
final String password2 = userPAssword2.getText().toString();
final String name = userName.getText().toString();
if(verificationUsername(name)){
showMessage("ass");
regBtn.setVisibility(View.VISIBLE);
loadingProgress.setVisibility(View.INVISIBLE);
}
public boolean verificationUsername (String equalto){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("Users").orderByChild("username").equalTo(equalto);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String TypeUser = dataSnapshot.child("username").getValue().toString();
if (dataSnapshot.exists()) {
System.out.println(TypeUser + "dssssssssssssssssssssssssddddddsssssssssssssssssssssss");
lola = dataSnapshot.toString();
showMessage("El nombre de usuario ya esta en uso, intenta con uno nuevo");
// dataSnapshot is the "issue" node with all children with id 0
for (DataSnapshot issue : dataSnapshot.getChildren()) {
// do something with the individual "issues"
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return false;
}
First of all I would recommend you to store the usernameUpperCase for all sentences become uppercase because Firebase Realtime is case sensitive.
So example for database something look like this:
username: Ticherhaz
usernameUpperCase: TICHERHAZ
I would prefer to use addListenerForSingleValueEvent because we want to read for once only.
public boolean verificationUsername (String equalto){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("Users").orderByChild("usernameUpperCase").equalTo(equalto.toUpperCase());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
//that's mean this username already exist
}
else {
//so username not exist yet, we create here new username.
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return false;
}
So, I recently learn about firebase database, and now i'm able to insert a data. I have this script which is to store data to my firebase .
mDatabase = FirebaseDatabase.getInstance().getReference("Biodata");
String userId = mDatabase.push().getKey();
Biodata bio = new Biodata("MyUser", "MyUser#email.com");
mDatabase.child(userId).setValue(bio);
The script above is in oncreate, so when i run the activty again and again the data will insert twice or more
and here is my firebase
Biodata
-LAuyJho4kTnJt5WuCtJ
Email: "MyUser#email.com"
Fullname: "MyUser"
My bidata class
#IgnoreExtraProperties
public class Biodata {
public String Fullname;
public String Email;
public Biodata() {
}
public Biodata(String Fullname, String Email) {
this.Fullname = Fullname;
this.Email = Email;
}
}
So, how can i prevent my app to insert same data twice ?
Please try below code may help you
public void setData(){
final DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference();
Query queryToGetData = dbRef.child("Biodata")
.orderByChild("Email").equalTo("MyUser#email.com");
queryToGetData.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.exists()){
String userId = dbRef.child("Biodata").push().getKey();
Biodata bio = new Biodata("MyUser", "MyUser#email.com");
dbRef.child("Biodata").child(userId).setValue(bio);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
First of all, you don't have to call it on the onCreate method. But theres another easy way for not creating duplicates. You have to create a random key for each user. Like, say emails id is unique for all users. So
mDatabase = FirebaseDatabase.getInstance().getReference("Biodata");
Biodata bio = new Biodata("MyUser", "MyUser#email.com");
mDatabase.child("MyUser#email.com").setValue(bio);
In this way, the user's details are under their own email id. It will be easier for u to get the details too. Also, this will not create duplicates, since the email id is unique. In firebase it will look like this:
Biodata
MyUser#email.com
Email: "MyUser#email.com"
Fullname: "MyUser"
So later if you want to get the users name, you just have to
DatabaseReference ref= mDatabase.child("MyUser#email.com");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Biodata bio = dataSnapshot.getValue(Biodata .class);
// and bio.getName() for getting the name
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
You should not add the email as a parent node or you will get an error.
First you are adding data twice, it is because you have this under onCreate(), it should be under a button or any event that can occur.
Second, you are generating a random id using push() so every time onCreate() is invoked new data will be added since push() is used to separate records.
To prevent this problem, add the creation of a user under a button (example under a Sign up button).
If you want to keep it under onCreate() then do the following:
mDatabase = FirebaseDatabase.getInstance().getReference("User");
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
String userId=user.getUid();
Biodata bio = new Biodata("MyUser", "MyUser#email.com");
mDatabase.child(userId).setValue(bio);
The above will work if you use firebase authentication and also after login of the user. The getUid() will retrieve the user id from the firebase authentication which is unique for each user. Then you will be able to add it to the database.
When the user logon with your google account for the first time in the app, I made this activity to create the user in the database. It's working, but are creating more than one user in the database, and I don't know why.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account);
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() == null) {
goLogInScreen();
} else {
final String userGoogleEmail = firebaseAuth.getCurrentUser().getEmail();
databaseUser.orderByChild("userEmail").equalTo(userGoogleEmail).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
//User already exists
} else {
//Can create new user
String id = databaseUser.push().getKey();
User user = new User(id, userGoogleEmail, null);
databaseUser.child(id).setValue(user);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
};
This is happening because your are using as an identifier the key generated by the push() method and not another identifier and this is actually creating the user again, even if exists in your database.
What i'm recomending you to do, is to change a little bit the logic of saving the data in your database. So in order to solve your problem, i recomand you using in stead of that key, the email address as an identifier, because is also unique. Your database should look like this:
Firebase-database
|
--- Users
|
--- jon#email,com
| |
| --- //data
|
--- jack#email,com
|
--- //data
As you probably see, i have saved the email addreees in the Firebase database using , (comma) and not . (dot).
name#email.com -> name#email,com
This is because Firebase does not allow symbols like . in the key name. So to store the values like this, the encoded email is required. To achieve this, i recomand you using the following methods:
String encodeUserEmail(String userEmail) {
return userEmail.replace(".", ",");
}
String decodeUserEmail(String userEmail) {
return userEmail.replace(",", ".");
}
To verify if a user exists, simply put the a listeenr on the Users node and use exists() method on the dataSnapshot object like this:
DatabaseReference usersRef = usersDatabaseReference.child(userEmail);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()) {
//create user
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(valueEventListener);
Hope this solves your problem.