check if data exist in Firebase Database - java

I want to check if data already exists in firebase database
this is my code to show data from firebase database :
databaseCars.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
carsList.clear();
for(DataSnapshot carSnapshot : dataSnapshot.getChildren()){
Cars cars = carSnapshot.getValue(Cars.class);
carsList.add(cars);
}
ArrayAdapter adapter = new CarsList(listView_Car.this,carsList);
listViewCars.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});

Can you try adding
if (dataSnapshot.hasChild(dataToAdd)) {
// data exist
}
Doc: https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot.html#haschild

Related

Show list of users with comparison two references in Android Firebase

In Firebase I have the "users" where I save all users' information.
Now I want to show someone I like in the "Favor".
This is "Favors"
In "Favor", only my ID and people ID I added to the favor list
And this is "users":
In "users", I have all users' information inside people's ID
And this is my code to show all users
database.getReference().child("users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
users.clear();
for(DataSnapshot snapshot1: snapshot.getChildren()){
User user= snapshot1.getValue(User.class);
if(!user.getUid().equals(FirebaseAuth.getInstance().getUid()) && hasChat != null)
users.add(user);
}
binding.recyclerView.hideShimmerAdapter();
usersAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
And this code i'm trying to show favor list, but it's show blank:
database.getReference().child("users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
users.clear();
for (DataSnapshot snapshot1 : snapshot.getChildren()) {
User user = snapshot1.getValue(User.class);
if (!user.getUid().equals(FirebaseAuth.getInstance().getUid()) && user.getUid().equals(database.getReference().child("Favors").getKey()))
users.add(user);
}
binding.recyclerView.hideShimmerAdapter();
usersAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});

Iterate, Check for condition & delete accordingly : Firebase Realtime

I'm using Firebase realtime database. Below is the structure
Problem Statement: Over a list of "Users", I need to delete child who's having coins = 0
So far I'm stuck here
DatabaseReference deleteRef = dbref.child("Users").child("coins");
Query deleteQuery = deleteRef.orderByValue().equalTo("0");
deleteQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
child.getRef().setValue(null);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
Any help will be appreciated :)
You need to order the list by the child coins like here:
DatabaseReference deleteRef = dbref.child("Users");
Query deleteQuery = deleteRef.orderByChild("coins").equalTo("0");
deleteQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
child.getRef().setValue(null);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});

How to retrieve this data from firebase database

I want to get to a listview the data on "Categorias" folder, but i try everthing and i can't do this.
Fragment code:
myRef.addValueEventListener(new ValueEventListener() {
public static final String TAG = "TNW";
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
Map<String, Object> td = (HashMap<String,Object>) dataSnapshot.getValue();
list3 values = td.values();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getActivity().getApplicationContext(), "Ese usuario ya existe ", Toast.LENGTH_SHORT).show();
}
});
Its very simple, here is the code to fetch your values.
DatabaseReference db = FirebaseDatabase.getInstance().getReference("people");
db.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds: dataSnapshot.getChildren()){
//get the categorias node
DataSnapshot dsCategorias = ds.child("categorias");
//loop inside the categorias node for all children
for(DataSnapshot dbValSnapshot: dsCategorias.getChildren()){
//Assuming all children have only boolean values
//getting the key and the values
String key = dbValSnapshot.getKey();
boolean value = dbValSnapshot.getValue(Boolean.class);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Let me know if you are not able to understand any part of my code. Thanks

Model Class returns null

[model class is returning null, data is coming from Firebase database but upon getting imageUrl its giving null.
Actually, I am trying to get images urls from database which are previously saved.
firebaseDatabase=FirebaseDatabase.getInstance();
databaseReference=firebaseDatabase.getInstance().
getReference("Catagories");
mupload=new ArrayList<>();`
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot post : dataSnapshot.getChildren())
{
Upload upload=post.getValue(Upload.class);
mupload.add(upload);
}
customQuoteAdapter=new CustomQuoteAdapter( Images.this,
mupload);
recyclerView.setAdapter(customQuoteAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getApplicationContext(),
"ERROR"+databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
You have a bussiness (sic) level in your JSON, that you're not handling in your code. The simplest way to fix this is to attach your listener to that bussiness node:
databaseReference=firebaseDatabase.getInstance().getReference("Catagories/Bussiness");
mupload=new ArrayList<>();`
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot post : dataSnapshot.getChildren()) {
Upload upload=post.getValue(Upload.class);
mupload.add(upload);
}
customQuoteAdapter=new CustomQuoteAdapter( Images.this, mupload);
recyclerView.setAdapter(customQuoteAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), "ERROR"+databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
If you want to get all URLS for all nodes under Categories, you'll need to add a loop inside onDataChange. Something like:
databaseReference=firebaseDatabase.getInstance().getReference("Catagories");
mupload=new ArrayList<>();`
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot categorySnapshot : dataSnapshot.getChildren()) {
for(DataSnapshot linkSnapshot : categorySnapshot.getChildren()) {
Upload upload=linkSnapshot.getValue(Upload.class);
mupload.add(upload);
}
}
customQuoteAdapter=new CustomQuoteAdapter( Images.this, mupload);
recyclerView.setAdapter(customQuoteAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), "ERROR"+databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
Should it be?
public String getImageUrl() {
return this.imageUrl;
}

how to get string array from firebase realtime database

databaseReference = FirebaseDatabase.getInstance().getReference("/sample");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Log.d(TAG, "onDataChange: dataSnapshot "+dataSnapshot.getValue());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I'm new to android app development and firebase as well. i m fetching data from sample node and getting DataSnapshot value like below.
{size=[Small, Large, Ex-Large], type=[Type 1, Type 2], color=[Red, Green, Blue], category=[T-Shirt, Jeans, Sweater]}
need some expect help, any suggestion will greatly appreciated.
Thanks
To retrieve values separately, you can use a code like this:
databaseReference.child("category").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (int i=0;i<3;i++) {
// category is an ArrayList you can declare above
category.add(dataSnapshot.child(String.valueOf(i)).getValue(String.class));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) { // Do something for this
}
});
Similarly you can add values of other nodes in your other ArrayLists, just by changing the value of Childs in this code.
Firebase has no native support for arrays. If you store an array, it really gets stored as an "object" with integers as the key names.
// we send this
['hello', 'world']
// Firebase stores this
{0: 'hello', 1: 'world'}
Best Practices: Arrays in Firebase
// TRY THIS
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
youNameArray = new ArrayList<>();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
String data = snapshot.getValue(String.class);
youNameArray.add(data);
}
Log.v("asdf", "First data : " + youNameArray.get(0));
}
Something like this:
databaseReference = FirebaseDatabase.getInstance().getReference("/sample");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot sampleSnapshot: dataSnapshot.getChildren()) {
Log.d(TAG, "onDataChange: sampleSnapshot "+sampleSnapshot.getKey()+" = "+sampleSnapshot.getValue());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
The difference is that in my answer I loop over dataSnapshot.getChildren() to get each individual sample snapshot. The sampleSnapshot.getValue() call should return a List.
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference refence = database.getReference();
refence.addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot snapshot) {
// TODO Auto-generated method stub
ArrayList array= new ArrayList<>();
for (DataSnapshot ds : snapshot.getChildren()){
String data = ds.getValue().toString();
array.add(data);
}
System.out.println(array);
}
#Override
public void onCancelled(DatabaseError error) {
// TODO Auto-generated method stub
}
});
In my case String.class does not work instead .toString method works
String data = ds.getValue().toString();

Categories