How to get Unique Key of childs in firebase - android

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

Related

Android Studio dataSnapshot exists but nothing is getting printed Firebase

I'm confused as to why this is not working and I have tried debugging it a lot and I have no idea why is this not working
FirebaseDatabase.getInstance().getReference().child("users").child("name").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Log.d("dataSnapshot", "exists");
for (DataSnapshot snapshot1 : dataSnapshot.getChildren()) {
Log.d("inside snapshot", "snapshot not null");
String name = snapshot1.getValue().toString();
Log.d("user created", "snapshot not null");
try {
Log.d("name", name);
Log.d("decrypt", aes.Decrypt(name));
} catch (UnsupportedEncodingException e) {
Toast.makeText(EnterName.this, "Exception", Toast.LENGTH_LONG);
e.printStackTrace();
}
Toast.makeText(EnterName.this, "logged", Toast.LENGTH_LONG);
}
}
else
{
Toast.makeText(EnterName.this,"doesnt exist", Toast.LENGTH_SHORT);
}
}
I'm getting the log that dataSnapshot exists but nothing after that. Firebase data is
Anyone has any idea? Thank you.
You're listening to just the users/name property, which means you get a snapshot with the key name and a string value "check". A string value doesn't have any children, so dataSnapshot.getChildren() returns an empty list.
To print the value of your snapshot:
FirebaseDatabase.getInstance().getReference().child("users").child("name").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Log.d("dataSnapshot", dataSnapshot.getValue(String.class));
}
...

Filtering Firebase Database on button click returns single Recycle View listItem

I want ListView to show only that data which has company name equal to the one entered in EditText on Search Button Click :
Button Click Event -
Button btnSearch = (Button) findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText objCompany = (EditText) findViewById(R.id.filterEdit);
mMessagesDatabaseReference.orderByChild("company").equalTo(objCompany.getText().toString()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for(DataSnapshot d1 : dataSnapshot.getChildren()) {
for(DataSnapshot d2 : d1.child("company").getChildren()) {
postAdapterObject.clear();
// Get the value from the DataSnapshot and add it to the item list
post itemObject = d1.getValue(post.class);
//this is where data from database is entered into a list of objects
postAdapterObject.add(itemObject);
postAdapterObject.notifyDataSetChanged();
}
}
Toast.makeText(MainActivity.this, "Data Filtered", Toast.LENGTH_LONG).show();
}
else{
postAdapterObject.clear();
postAdapterObject.notifyDataSetChanged();
Toast.makeText(MainActivity.this, "Data Not Found!", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
postAdapterObject.clear();
postAdapterObject.notifyDataSetChanged();
Toast.makeText(MainActivity.this, "No Data Found! Try with some other data entry", Toast.LENGTH_LONG).show();
}
});
}
});
It looks like you're looping one level too deep in your JSON. This is a lot simpler, and should be close to what you need:
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
postAdapterObject.clear();
for(DataSnapshot d1: dataSnapshot.getChildren()) {
post itemObject = d1.getValue(post.class);
postAdapterObject.add(itemObject);
}
postAdapterObject.notifyDataSetChanged();
if (postAdapterObject.size() > 0) { // TODO: write this condition
Toast.makeText(MainActivity.this, "Data Filtered", Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this, "Data Not Found!", Toast.LENGTH_LONG).show();
}
}
You may need to fix the check in if (postAdapterObject.size() > 0) {, since it depends on the type of postAdapterObject.

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 to retrieve data and specific user data from the Firebase

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

How to check if firebase query is empty

I want to delete the data from Firebase before unauthorizing. The problem is that mFirebaseRef.unauth() works only if query is not empty. But I need it to work even if query is empty.
final Firebase pushNotificationRef = new Firebase(Constant.FIREBASE_URL_PUSHNOTIFICATIONS);
final Query queryRef = pushNotificationRef.orderByChild("deviceToken").equalTo(token);
queryRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot.exists()) {
Log.e("MyTag", dataSnapshot.getKey());
pushNotificationRef.child(dataSnapshot.getKey()).removeValue();
}
mFirebaseRef.unauth();
}
use this...
if (dataSnapshot.exists())
// user found
else
// user not found
demo example
Query query = dbstud.child("users").orderByChild("name").equalTo("XYZ");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Toast.makeText(getApplicationContext(), "id = " + snapshot.getKey(), Toast.LENGTH_LONG).show();
}
}
else {
Toast.makeText(getApplicationContext(), "User Not found ", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});

Categories

Resources