Check and compare particular data in app from Firebase data - android

I'm making an app to store user data into Firebase realtime database. I've successfully saved and retrieved data to and from firebase database. Now suppose user have stored his name in database. Then i want to check if the name exists or not.
And if it exists, then is that name the same as the name stored in a string in my app or not?
Any idea? How to do this.
Code used for saving user's name
databaseReference.child("users").child(uniqueID).setValue(name);
Is there any way to get this specific value from database? Like is there anything like getValue() or something?
Below is the screenshot of my app:-
Here is the sequence of my ap:-
First user will register, then login.
When user login for the first time, we will ask him to set a 4 digit passcode which will be stored in firebase database.
Aboveis firebase screenshot:-
This is how i store the passcode.
now when user will click on "SET", we will save entered passcode to database and redirect user to mainActivity. But when user will reopen our app, we will check if there is any passcode stored in our database for this particular user or not. If passcode is stored then we will directly send him to passcode verification activity where user will enter passcode and we have to check if the passcode in out and the user entered passcode is same or not. but if there is no passcode in database then we will open this Setup Passcode activity again and ask him to set up a passcode.

Yes, you can use orderByChild() query along with equalTo() to check whether the data of the user exists in database or not.
This code not only checks if the passcode is present but also that it is correct or not.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("password").child("passcodes");
ref.orderByChild("passcode").equalTo(passCodeYouHave).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists())
// passcode is present, and is correct
else
// incorrect passcode or no passcode
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Here passCodeYouHave is the passcode of the user you have in the app, and you can use it to check in firebase, if such name exists in the node named passcode.
This code will not check the correct passcode, it will just check if there is a passcode or not.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("password").child("passcodes");
ref.orderByChild("passcode").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists())
// passcode is present, so go to activity for checking the passcode
else
// no passcode is present so go for activity to set up new passcode
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});

Related

How can we delete firebase user if he doesn't verify email?

I want to delete user from firebase authentication and also want to delete data from real-time database if the user doesn't verify email address with in 1 hours. Deleting a user is easy but if doesn't verify in 1 hour then how could I do this? The problem is that firebase is server less.
Write and deploy a scheduled function that periodically:
Queries your database for users who have not verified (you will need a child to record that).
Delete the database record and also delete the user account.
You will need to use the Firebase Admin SDK for both of these steps.
It's so easy! just create a real-time database of the unverified user database. and when the user signup the time will be also registered in the database. So when the apps start it check the unverified users and there you write the if-else statement if the difference between time is greater than 1hour the user will be deleted.
It's so simple as I said :)
Run firebaseAuth.getCurrentUser().isEmailVerified() function inside signInWithEmailAndPassword function to see if user is verified or not. if user is verfied then only create users database otherwise give an exception and break the function, it won't save unverified users data.
firebaseAuth.signInWithEmailAndPassword(Email,Pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
if (firebaseAuth.getCurrentUser().isEmailVerified()){
FirebaseUser user = firebaseAuth.getCurrentUser();
Uid = user.getUid();
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (!snapshot.hasChild(Uid)){
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(Uid);
HashMap<String,String> userMap = new HashMap<>();
userMap.put("Name","default");
userMap.put("email",Email);
databaseReference.setValue(userMap).addOnCompleteListener(new OnCompleteListener<Void>() {
//call your function here when user sign in first time after email verification
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
//call your function when user already registered and verified
//and already saved his information to database
}else{
//show your exception here
}
}else{
//show your exception here
}
}
});

UserId returning null

My app is returning me a null UID. At the time of registration, I'm using phone authentication to registered the and getting some custom field from the user which I save under the current user UID in the Firebase database. In the registration activity, it is giving me the UID perfectly, but when I log in the user through credential and on successful login it diverts the user to MainActivity, and it gives me null at that time.
Note
I am logging in the user by matching his/her username and password from the DB which I saved at registration. Is this the issue that I'm not getting UID that I'm not using any Firebase signin method? Rather, I am matching the values from the DB in the login activity and on successful match I logged in the user. Because if there is any other issue it won't give me a UID on Register Activity also, but after login it gives me null at Main Activity and Profile Activity.
Signin Code
FirebaseDatabase.getInstance().getReference().child("Content").child("Profiles").orderByChild("mobile_number").equalTo(mobileNum)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot user : dataSnapshot.getChildren()) {
Profiles profiles = user.getValue(Profiles.class);
if (profiles.getPassword().equals(password)) {
progressDialog.dismiss();
startActivity(new Intent(LoginActivity.this, MainActivity.class));
}
else {
progressDialog.dismiss();
HelperClass.showSnakbarMsg(rootView, "Username or password did not match. Please try again.");
}
}
}
Code not working
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
String userId = firebaseAuth.getUid();
Log.d("user",userId);
It's returning me null in Main Activity after login.
If I log in by matching values in a Firebase realtime database, do I get the UID of the user or for getting the UID? It is a must to use some Firebase authentication to sign in like (email/password or phone authentication or Gmail sign in, etc.)
After a lot of debugging and going through Firebase documentation, I got to this conclusion that to get the user UID, it is a must to use any Firebase authentication method to login. I'm getting null because I am matching values from the Firebase database and if they matched I logged the user in.
In all this process, Firebase didn't get to know that who I'm. Because I'm only using its DB, not its official signin methods, like email, password, etc. So this is the reason I am getting a null UID.
And as far as for registration I am using Phoneauthentication to verify the number after verification automatically. Firebase gives me a UID for that user as I'm using its authentication so for that time it recognizes me as a user and assigns me a unique number which I get and made parent node for custom data I save with Firebase authentication at time of registering.
And then in Login, while matching the user credentials, I can get that UID as its parent node of my values by this code and you use it anywhere by saving it in shared preferences or passing through intent from activity to activity.
FirebaseDatabase.getInstance().getReference().child("Content").child("Profiles").orderByChild("mobile_number").equalTo(mobileNum)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot user : dataSnapshot.getChildren()) {
** String key = user.getKey(); **
Toast.makeText(LoginActivity.this, key, Toast.LENGTH_SHORT).show();
Profiles profiles = user.getValue(Profiles.class);
if (profiles.getPassword().equals(password)) {
progressDialog.dismiss();
startActivity(new Intent(LoginActivity.this, MainActivity.class));
}

OrderByChild adding one more element to the result

I'm trying to get just the events that a certain user has, the thing is that after doing orderByChild() it's filtering one more event that I don't want.
The code
//I find the user that belongs to a certain Tutor
mDatabase.child("tutorjugadores").child(mAuth.getCurrentUser().getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshotJugador) {
for(final DataSnapshot snapshotJugadoresTutor : dataSnapshotJugador.getChildren()){
if(dataSnapshotJugador.exists()){
//If the user has not assisted to a certain event, I get the user that belongs to the user and get the event ID
mDatabase.child("asistenciasjugadores").orderByChild(snapshotJugadoresTutor.getKey()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshotEvento) {
for(DataSnapshot snapshotEventos : dataSnapshotEvento.getChildren()){
//Getting the event key from that user
String eventKey = snapshotEventos.getKey();
Log.d(TAG, "Event : "+eventKey + " of the user "+snapshotJugadoresTutor.getKey());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Now, this is my database structure
The problem
Now, when I run this code and execute the log to get the event for the user 2UHHZWR6B8P9XJPuLYrAg6aEgN63, I'm getting one more event that does not belong to that user, that event is this one -LU930PpCaQXT8CvUbc8
My log
Event : -LU930PpCaQXT8CvUbc8 of the user 2UHHZWR6B8P9XJPuLYrAg6aEgN63
Event : -LTRz61EcBUx-RLSSEaU of the user 2UHHZWR6B8P9XJPuLYrAg6aEgN63
Event : -LTSGFGdW1nQbtd9HOBh of the user 2UHHZWR6B8P9XJPuLYrAg6aEgN63
Event : -LTSIG_lqckgHEZ1q9YS of the user 2UHHZWR6B8P9XJPuLYrAg6aEgN63
As you can see, is listing all the events for that user, but that user only has 3 events associated with it.
When I order with this line
.orderByChild(snapshotJugadoresTutor.getKey())
I'm expecting to get just the nodes with the userID 2UHHZWR6B8P9XJPuLYrAg6aEgN63 and then loop and get each event ID from that user, but instead, I'm getting the event ID from this user as well GVD0bLDf41VDdraN67mXjAS6KPk1.
You can't filter with a string by only using JSON based databases like Firebase.
And orderByChild only changes the sorting of the returned values. So you are basically ordering all the values under that key, there is no filtering going on.
After this point you have 3 options to go on.
Option 1 - Not efficient, recommended for only small apps:
You can order all the values and do the filter afterwards.
Option 2 - Recommended:
You can change your data structure. Create another node like "UserEvents". Under it store UID's. And under that UID's there should only be that user's events.
Option 3 - Recommended and functional:
You can use Elasticsearch. It's great for complex queries. You can use it with Firebase with Google Cloud Functions after you switched to " Pay as you go " plan or you can integrate another server with Firebase database by using Flashlight extension.

How can I check if the phone number already exists in the Firebase Authentication? [duplicate]

This question already has answers here:
How can I detect if user first time in Firebase [duplicate]
(4 answers)
Closed 4 years ago.
I have used the firebase authentication with phone number in my android app. But firebase doesn't give different functions for sign in and sign up like the email password authentication. How can I check if the user already exists?
What you can do in this case is that, store the phone number of every signed up user in the phone node of your Firebase database.
Then when signing a new user from a phone number, you can run a check in your phone node, that wether the phone number exists or not.
To store the phone number in a node named phone in your database, you can use a code like this:
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential){
mAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
// you may be using a signIn with phone number like this, now here you can save the phone number in your database
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("phone");
ref.child(phoneNumber).setValue(phoneNumber);
}
else if(task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
Toast.makeText(MainActivity.this, "OTP is incorrect", Toast.LENGTH_SHORT).show();
}
}
});
}
In the above code, phoneNumber is the number of the user you're signing up. Also I have used the heading name and value same, and that is, phoneNumber itself. You can use a name or anything else, you want.
Now when you're signing up a new user, you should run a check in your phone node in your database, using the following piece of code. You can add instance to this new method in the code above.
boolean checkForPhoneNumber(String number){
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.orderByChild("phone").equalTo(number).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists())
return true;
else
return false;
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}

Getting info of user off firebase Android

I'm trying to create an app on Android that stores user contact info.
When the user creates a "contact card" to send to another user, I'd like it to display things I stored when registering the user, name, year, number etc.
When I push, firebase creates a unique key, and when I create a FirebaseUser it creates a uid. for ease, I save the uid as part of the user structure.
I'm now attempting to access that user using the uid, unfortunately the uid is not the key.
So, I'm trying to query.
I create a Firebaseuser
currentUser = firebaseAuth.getCurrentUser.getUid.
then I try to query by
DatabaseReference ref = firebase.getinstance().getReference("user);
ref.orderByChild("Uid").equalto(currentUser.getUid());
Is this correct? after I try to add a single valuelistener to obtain the actual values inside this user. Unfortunately this crashes. Can someone point me in the right direction?
You can use the user uid as the key to save the user info like this:
private DatabaseReference mDatabase;
// ...
mDatabase = FirebaseDatabase.getInstance().getReference();
User user = new User(name, email);
mDatabase.child("users").child(userUid).setValue(user);
Then you can get the user info like this
ValueEventListener userListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get User object and use the values to update the UI
User user= dataSnapshot.getValue(User.class);
// ...
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting User failed, log a message
Log.w(TAG, "loadUser:onCancelled", databaseError.toException());
// ...
}
};
mDatabase.child("users").child(userUid).addValueEventListener(userListener);
If this doesn't work, write the error log on the OP please ;)

Categories

Resources