Fetch and Compare Key and Value from Firebase Realtime Database - android

I'm trying to make an app in which user store his Data. I've used user shared preferences to save user login details but still for security purpose, i made an activity(Verify Passcode Activity) that ask user Passcode to allow access on the data. Now i'm able to save, fetch and delete data. But in my Verify Passcode Activity, i just want to fetch that particular key and value where passcode is stored. I don't want to fetch complete data in Verify Passcode Activity.
Below is the code which i used to save passcode to database:-
databaseReference.child(uniqueID).setValue(passcode);
Below is the code i'm tried to fetch only passcode:-
dbreference.child(uniqueID).orderByChild("passcode").equalTo(pass).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
Toast.makeText(getApplicationContext(), "Data exist", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Data doesn't exist", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Here uniqueID is "abhishek88666kumar"and pass is a variable used for getText().
Here is the screenshot of my Firebase Database :-
Database Screenshot
Here is Verify Passcode Activity Screenshot:-
Please have a look at Database Screenshot and Verify Passcode Activity Screenshot.
Agenda:
getText() from textView inside activity.
getValue from firebase realtime database (only for current user. 'abhishek88666kumar' in our case).
compare if 1 and 2 are same or not. (If same then redirect to MainActivity else show error.)
Please tell me what i'm doing wrong.

Thanks to all for your help :) Your answer didn't worked for me but with the help of your answers and my few knowledge, I made a solution for my problem myself.
Here is the code that matches my requirement. This code is working exactly how I wanted.
dbreference = FirebaseDatabase.getInstance().getReference("passcodes");
Query query = dbreference.orderByKey().equalTo(currentUser); //current user is "abhishek88666kumar" in this case.
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
String passcode = txtPasscode.getText().toString;//Passcode is 1234 in this case.
String fetchedValue = "";
for (DataSnapshot snap : dataSnapshot.getChildren()){
fetchedValue = (String) snap.getValue();
}
if (!passcode.equals(fetchedValue)){
Toast.makeText(getApplicationContext(), "Passcode doesn't match.", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Passcode matched.", Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(getApplicationContext(), "No passcode found for this user", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});

Assuming pass is a value like 1234, this line:
dbreference.child(uniqueID).orderByChild("passcode").equalTo(pass).addListenerForSingleValueEvent(...
Should be:
FirebaseDatabase.getInstance().getReference("passcodes").orderByValue().equalTo(pass).addListenerForSingleValueEvent(...
This way the DataSnapshot will contain all child nodes of passcodes that have the value 1234, i.e. "abhishek88666kumar" in your JSON sample.
Also be sure to study the documentation on sorting and filtering data.

This is the first way to compare firebase data.
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
passcode = editText.getText().toString();
Toast.makeText(getApplicationContext(), "Data :"+passcode, Toast.LENGTH_LONG).show();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("passcode");
Query applesQuery = ref.orderByValue().equalTo(passcode);
applesQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
Toast.makeText(getApplicationContext(), "Data exist", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Data doesn't exist"+passcode, Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Log.e(TAG, "onCancelled", databaseError.toException());
}
});
}
});
This is the second way to compare firebase data.
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
check = editText.getText().toString();
Toast.makeText(getApplicationContext(), "Data :"+check, Toast.LENGTH_LONG).show();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("passcode");
// Query applesQuery = ref.child("Customers").orderByChild("abhishek88666kumar").equalTo(passcode);
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
if(map.get("abhishek88666kumar")!=null){
passcode = map.get("abhishek88666kumar").toString();
if (passcode.equals(check))
{
Toast.makeText(getApplicationContext(), "Data exist", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(), "Data doesn't exist"+check, Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Log.e(TAG, "onCancelled", databaseError.toException());
}
});
}
});
Both are working.
Hope it's help full for you.
thank you.

Related

How to create query for searching enrollment number into the Firebase realtime database for if user entered enrollment number exist or not

I've created String userenrollment that store user entered enrollment number into it! and My firebase real time database looks like .
and I tried one query but it directly goes to else block saying data doesn't exist!
ref = FirebaseDatabase.getInstance().getReference();
Query query = ref.child("Information").orderByChild("enrollment").equalTo(userenrollment);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot snapshot) {
if (snapshot.getChildrenCount()>0) {
Toast.makeText(loginstudentdemo.this, "User exist!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(loginstudentdemo.this, "User doesn't exist", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError error) {
Toast.makeText(loginstudentdemo.this, "Database Error", Toast.LENGTH_SHORT).show();
}
});

Finding if Email and/or Username existing in Firebase - Android

I'm new to Firebase and Android so please be easy with me here.
I'm trying to validate if the username and/or email already in the DB.
The problem is that once the code finds out there no user with that username, he go to addUser() function that adds the username to the Fire-base.
I tried reading around the Android Studio Development and I get the manage single check for either Email or Username but not both.
old code :
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("Users").child(""+Username).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
// User name already exists.
Toast.makeText(MainActivity.this, "Username already found in DB, try different Username", Toast.LENGTH_SHORT).show();
etUsername.setText("");
etUsername.hasFocus();
} else {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("Users").child(""+Email).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// Email already exists
Toast.makeText(MainActivity.this, "Email already found in DB, try different Email", Toast.LENGTH_SHORT).show();
etEmail.setText("");
etEmail.hasFocus();
}else{
// if here, mean all good
addUser(Username, Password, Fname, Phone, Lname, Email);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Can someone help or direct me to an article that demonstrate 2 checks with Firebase?
edit: I found out that I need to first to orderByChild the index im searching at so I solved the Email part but the Username part is still tricky as I'm getting back an Object instead of a String and I can't convert it
New Code:
ref.equalTo(Username).addListenerForSingleValueEvent(new ValueEventListener() {
String check = (String)ref.equalTo(Username).toString();
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i("Message","username is:"+check);
if(dataSnapshot.exists()){
Log.i("user","you check if user and got it, mean there is one in DB");
// User name already exists.
Toast.makeText(MainActivity.this, "Username already found in DB, try different Username", Toast.LENGTH_SHORT).show();
etUsername.setText("");
etUsername.hasFocus();
} else {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users");
ref.orderByChild("Email").equalTo(Email).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// Email already exists
Toast.makeText(MainActivity.this, "Email already found in DB, try different Email", Toast.LENGTH_SHORT).show();
etEmail.setText("");
etEmail.hasFocus();
}else{
// if here, mean all good
addUser(Username, Password, Fname, Phone, Lname, Email);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
So if mixing both of my codes you will get the result I wanted.
In order to check if a username is in the DB I used the first part of my code and for the Email the second one
Full code for check if username and/or Email is used in Fire-base
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users");
ref.child(""+Username).addListenerForSingleValueEvent(new ValueEventListener() {
String check = (String)ref.equalTo(Username).toString();
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i("Message","username is:"+check);
if(dataSnapshot.exists()){
Log.i("user","you check if user and got it, mean there is one in DB");
// User name already exists.
Toast.makeText(MainActivity.this, "Username already found in DB, try different Username", Toast.LENGTH_SHORT).show();
etUsername.setText("");
etUsername.hasFocus();
} else {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users");
ref.orderByChild("Email").equalTo(Email).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// Email already exists
Toast.makeText(MainActivity.this, "Email already found in DB, try different Email", Toast.LENGTH_SHORT).show();
etEmail.setText("");
etEmail.hasFocus();
}else{
// if here, mean all good
addUser(Username, Password, Fname, Phone, Lname, Email);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
if you have questions, feel free to ask :)

How can I check If the data already exists in the database?

I'm developing a reservation mobile app wherein when I click the checkAvailability, it will check if the data already exists in the database. My problem is that I don't know how to access since the key is randomly generated. There is a lot of similar questions to mine but no solutions has been working for me.
Firebase Database(Screenshot):
btnAvailability.setOnClickListener
btnAvailability.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Query userQuery = database.getInstance().getReference().child("Requests")
.orderByChild("order/0");
userQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String type = dataSnapshot.child("checkIn").getValue().toString();
String type2 = dataSnapshot.child("productName").getValue().toString();
if(type.equals(checkInTV.getText().toString()) && type2.equals(beach_name.getText().toString())) {
Toast.makeText(details.this, "Not Available", Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(details.this, "Available", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
From the looks of it, you're trying to check of there is a child that has order/0 with a specific checkIn and productName under Requests. In your current data structure you can do that with:
Query userQuery = database.getInstance().getReference().child("Requests")
.orderByChild("order/0");
userQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
String type = snapshot.child("checkIn").getValue().toString();
String type2 = snapshot.child("productName").getValue().toString();
if(type.equals("Saturday, April 20, 2019") && type2.equals("The Mansion")) {
Toast.makeText(details.this, "Not Available", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(details.this, "Available", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException()
}
});
Differences from your code:
I have a loop inside onDataChange, since a query can have multiple results.
I hardcoded the date to rule out the problem being caused by the way you input the data in the text view.
I handle onCancelled, since ignoring errors is just a bad idea.
A more efficient way to accomplish the same is to have Firebase do part of the query, like this:
Query userQuery = database.getInstance().getReference().child("Requests")
.orderByChild("order/0/checkIn").equalTo("Saturday, April 20, 2019");
userQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
String type2 = snapshot.child("productName").getValue().toString();
if(type2.equals("The Mansion")) {
Toast.makeText(details.this, "Not Available", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(details.this, "Available", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException()
}
});
In here the change is:
I moved part of the check into the query, so that Firebase can perform that filter on the server. This means it has to download less data to the client, making it both faster and cheaper.
You'll still have to filter the second value client-side, since Firebase queries can only order/filter on one property. For more on this, see Query based on multiple where clauses in Firebase.
Note that you're querying double nested data. While you can get this to work for a specific order (orders/0 in this example), if you can have multiple orders in a request, Firebase won't be able to query across all of them.
For more on this and a solution, see: Firebase Query Double Nested
I'd also recommend reading my answers about modeling categories, because I have a feeling you'll need this soon: Firebase query if child of child contains a value
While storing data you need make user email id as first parameter so that you can access data based on user.
{"reuest":{"xyz#gmail.com":{"orders":[{"checkin":"21:29"},{"checkin":"2:19"}]},"abc#gmail.com":{"orders":[{"checkin":"21:29"},{"checkin":"2:19"}]}}}
Finally found a solution on my problem.
btnAvailability.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Query userQuery = database.getInstance().getReference().child("Requests")
.orderByChild("order/0/checkIn").equalTo(checkInTV.getText().toString());
userQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
String type2 = snapshot.child("order/0/productName").getValue().toString();
if(type2.equals(beach_name.getText().toString())) {
Toast.makeText(details.this, "Not Available", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(details.this, "Available", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
});

Toast not working when data is not existing

My Toast not working when the data is not existing from Firebase database. What happen ?
public void searching(final String id){
DatabaseReference databaseReference = FirebaseDatabase.getInstance()
.getReference("Employee");
Query query = databaseReference.orderByChild("id").equalTo(id);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot data: dataSnapshot.getChildren()){
if(data.child("id").exists()) {
Employee employee = data.getValue(Employee.class);
hp.setText(employee.getPhoneNum());
address.setText(employee.getAddress());
fullName.setText(employee.getFullName());
Ic.setText(employee.getIcNum());
Sex.setText(employee.getSex());
emailVerify.setText(employee.getEmail());
getData.setVisibility(View.GONE);
update.setVisibility(View.VISIBLE);
fullName.setVisibility(View.VISIBLE);
Ic.setVisibility(View.VISIBLE);
tAddress.setVisibility(View.VISIBLE);
tPhone.setVisibility(View.VISIBLE);
hp.setVisibility(View.VISIBLE);
address.setVisibility(View.VISIBLE);
Sex.setVisibility(View.VISIBLE);
}else{
Toast.makeText(getContext(),"Please Enter Correct Employee ID",
Toast.LENGTH_SHORT).show();
return;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
It may be possible your query databaseReference.orderByChild("id").equalTo(id) this condition not able to getting any record so it will be not execute for loop so you may to check first the number of children are greater than 0 or not.
You can try this way Like :
if (dataSnapshot.dataSnapshot.getChildrenCount() > 0){
for(DataSnapshot data: dataSnapshot.getChildren()){
if(data.child("id").exists()) {
Employee employee = data.getValue(Employee.class);
hp.setText(employee.getPhoneNum());
address.setText(employee.getAddress());
fullName.setText(employee.getFullName());
Ic.setText(employee.getIcNum());
Sex.setText(employee.getSex());
emailVerify.setText(employee.getEmail());
getData.setVisibility(View.GONE);
update.setVisibility(View.VISIBLE);
fullName.setVisibility(View.VISIBLE);
Ic.setVisibility(View.VISIBLE);
tAddress.setVisibility(View.VISIBLE);
tPhone.setVisibility(View.VISIBLE);
hp.setVisibility(View.VISIBLE);
address.setVisibility(View.VISIBLE);
Sex.setVisibility(View.VISIBLE);
}else{
Toast.makeText(getContext(),"Please Enter Correct Employee ID",
Toast.LENGTH_SHORT).show();
return;
}
}
} else {
Toast.makeText(getContext(),"No data found.",
Toast.LENGTH_SHORT).show();
}
When dataSnapshot.getChildren() is empty you wont enter in your for block so Toast wont appear.

How can I retrieve some fields from my Firebase database before I push any changes to it?

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

Categories

Resources