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.
Related
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();
}
});
i am new to Firebase
so i have a scenario where i have to set a check that if a hotel is already present in FavouriteHotels Node, then this must Toast that this hotel is already present in FavouriteHotels Node else Just Store that clicked hotel. like in this code.
final String favHotel_Id = myRef.push().getKey();
myRef.child("Users").child(mUser.getUid())
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot userSnapshot : snapshot.getChildren()) {
if (!userSnapshot.child("FavouriteHotels").exists()){
Log.d(TAG, "onDataChange: "+userSnapshot.getChildren());
if (Objects.equals(hotelArrayList.get(position).getHotelName(), userSnapshot.child("Name").getValue() )) {
Toast.makeText(mContext, "Already saved to favourite hotels", Toast.LENGTH_SHORT).show();
} else {
if (favHotel_Id != null) {
myRef.child("Users").child(mUser.getUid()).child("FavouriteHotels").child(favHotel_Id).child("Name").setValue(hotelArrayList.get(position).getHotelName());
myRef.child("Users").child(mUser.getUid()).child("FavouriteHotels").child(favHotel_Id).child("Image").setValue(hotelArrayList.get(position).getImageID());
myRef.child("Users").child(mUser.getUid()).child("FavouriteHotels").child(favHotel_Id).child("rating").setValue(hotelArrayList.get(position).getHotelRating());
myRef.child("Users").child(mUser.getUid()).child("FavouriteHotels").child(favHotel_Id).child("Price").setValue(hotelArrayList.get(position).getHotelPrice());
}
}
}else {
Toast.makeText(mContext, "No Data Found", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
one thing i want to mention is, i am saving this hotel item with its properties from ArrayList where i am getting that
if (Objects.equals(hotelArrayList.get(position).getHotelName(), userSnapshot.child("Name").getValue() )) {
Toast.makeText(mContext, "Already saved to favourite hotels", Toast.LENGTH_SHORT).show();
} else {
if (favHotel_Id != null) {
myRef.child("Users").child(mUser.getUid()).child("FavouriteHotels").child(favHotel_Id).child("Name").setValue(hotelArrayList.get(position).getHotelName());
myRef.child("Users").child(mUser.getUid()).child("FavouriteHotels").child(favHotel_Id).child("Image").setValue(hotelArrayList.get(position).getImageID());
myRef.child("Users").child(mUser.getUid()).child("FavouriteHotels").child(favHotel_Id).child("rating").setValue(hotelArrayList.get(position).getHotelRating());
myRef.child("Users").child(mUser.getUid()).child("FavouriteHotels").child(favHotel_Id).child("Price").setValue(hotelArrayList.get(position).getHotelPrice());
}
}
i want to fetch the unique Key of hotel highlighted in circle and putting a check on the Name of hotel that if hotelArrayList.get(position).getHotelName(), userSnapshot.child("Name").getValue() then show me a toast that this hotel is already present in the db.
you can get the push key like this.
Query query = FirebaseDatabase.getInstance().getReference("your node path");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
String key = snapshot.getKey();
Log.i(TAG,key);
}
}
I am creating a phone node and storing user's number in that node at the time of sign up so that app asks him to sign up and does not send him verification code if he tries to sign in before signing up.
I tried firebase query to compare the number user enters with the phone node to check if the number exists or not.
if (v == btn_login) {
Toast.makeText(LoginActivity.this, "In Login Button", Toast.LENGTH_LONG).show();
String number = et_Phone.getText().toString().trim();
if (number.isEmpty() || number.length() < 10) {
et_Phone.setError("Valid number is required");
et_Phone.requestFocus();
return;
}
final String ph = "+92" + number.substring(1);
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("phone");
Query query = ref.orderByChild("phonenumber").equalTo(ph);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Toast.makeText(LoginActivity.this, ph.toString(), Toast.LENGTH_LONG).show();
sendVerificationCode(ph);
L1.setVisibility(View.GONE);
L2.setVisibility(View.VISIBLE);
} else {
et_Phone.setError("Please enter the number again");
et_Phone.setText("");
et_Phone.requestFocus();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
Firebase Query returns null every time
Your phone node has only a single property phonenumber. To find the property with the value you entered, use:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("phone");
Query query = ref.orderByValue().equalTo("+923234022022");
To use orderByChild("phonenumber") the location that you're querying needs to have multiple child nodes, each of which in turn has a phonenumber property. So something like:
users: {
uidOfUser1: {
name: "Sikandar Niaz",
phonenumber: "5557273456"
},
uidOfUser2: {
name: "Frank van Puffelen",
phonenumber: "5554159410"
}
}
Now in the above structure you can use orderByChild() to find the child nodes that have a specific phone number:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("users");
Query query = ref.orderByChild("phonenumber").equalTo("5557273456");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
System.out.println(userSnapshot.getKey())
System.out.println(userSnapshot.child("name").getValue(String.class))
}
}
...
This will print:
uidOfUser1
Sikandar Niaz
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.
I am having problem in retrieving data from firebase. I have one root user's node and then inside that root I have one userID child node. Inside that child node I am storing user information according to its blood group.
Now, what I want is to fetch the name and email according to blood group, say fetch all user data whose blood group is B+.
Also, please tell me on how to fetch all entries in the firebase and show on textView.
//show data on text view
datashow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("inside click", "onClick: ");
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference db = database.getReference();
db.child("users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
if (user == null) {
Log.e(TAG, "User data is null!");
return;
}
Iterable<DataSnapshot > children = dataSnapshot.getChildren();
Log.i("children", "onDataChange: " + children);
for(DataSnapshot child : children)
{
Map<String , String> map = (Map)child.getValue();
Log.i("inside", "onDataChange: " + map);
name = map.get("name");
email = map.get("email");
dateof = map.get("userDob");
showData(name , email , dateof );
Log.i("datasnap", "onDataChange: data snapshot " + name + email + dateof);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
this is my snapshot for Firebase database
enter image description here
db.child("users").orderByChild("userBloodGroup").equalTo("B+").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
List<User> data = new ArrayList<>();
if (dataSnapshot.exists()) {
for (DataSnapshot snapshot :
dataSnapshot.getChildren()) {
User element = snapshot.getValue(User.class);
element.setKey(snapshot.getKey());
data.add(element);
}
for (User user: data){
Log.i(TAG,"user name: " +user.getName());
Log.i(TAG,"user email: " +user.getEmail());
Log.i(TAG,"user dob: " +user.getUserDob());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.i(TAG, "loadPost:onCancelled", databaseError.toException());
}
});
To query for all users with the bloodGroup B+, use a Firebase Query:
firebaseReference("users").orderByChild("userBloodGroup").equalTo("B+")
To get all the data of the users, you could use a Listener to get all of them and put them in whatever TextView you need. You could check the documentation on Firebase on how they read data. https://firebase.google.com/docs/database/android/read-and-write