Android Java Firebase:
DatabaseReference root = FirebaseDatabase.getInstance().getReference();
DatabaseReference users = root.child("Users");
users.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.childExists("name")) {
// run some code
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
This is my code, but childexists is not a valid working method. What is a way to check? If there is something similar can I just fix it?
Either use hasChild():
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.hasChild("name")) {
// run some code
}
}
Or child().exists():
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.child("name").exists()) {
// run some code
}
}
Related
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();
}
});
I have this structure in my Firebase Real-time database :
How can I count the data and show it in my app, which listener shall I use to get all childrens?
There are a few ways in which you could achieve this.
I use the following way:
FirebaseDatabase.getInstance()
.getReference()
.child("demografi")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnap : dataSnapshot.getChildren()) {
YourObject object = dataSnap.getValue(YourObject.class);
// Use your object as needed
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
dataSnapshot returns the child referenced. Once you have it, all you have to do is iterate through them and you have access to "all children" as you wanted.
FirebaseDatabase.getInstance()
.getReference()
.child("demografi")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
/** Qty of data in demografi, this is what you want. */
long Count = dataSnapshot.getChildrenCount();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
if you want to monitor the count of data in realtime way,
you have to replace [addListenerForSingleValueEvent] with [addValueEventListener].
I will prefer this way -
String email, gender, nama;
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("demografi");
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
// To get children count
dataSnapshot.getChildrenCount();
email = dataSnapshot.child("email").getValue().toString();
gender = dataSnapshot.child("gender").getValue().toString();
nama = dataSnapshot.child("nama").getValue().toString();
// and so on..
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s){
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
If you don't have a model class, you can simply use the String class. So to get all child's data, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference demografiRef = rootRef.child("demografi");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String nama = ds.child("nama").getValue(String.class);
Log.d("TAG", nama);
}
Log.d("TAG", String.valueOf(dataSnapshot.getChildrenCount()));
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
demografiRef.addListenerForSingleValueEvent(valueEventListener);
The output in your logcat will be all the names of all your users. As you can see, there is a second log statement which will print the total number of your children.
FirebaseDatabase.getInstance().getReference("Block").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snap : dataSnapshot.getChildren()) {
if(snap.getKey().equals(myUID)){
FirebaseDatabase.getInstance().getReference("Block").child(myUID).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snap : dataSnapshot.getChildren()) {
if(snap.getKey().equals(list.get(position).getUid())){
FirebaseDatabase.getInstance().getReference("Block").child(myUID).child(list.get(position).getUid()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snap : dataSnapshot.getChildren()) {
if(snap.getValue().equals("1")){
call_method();
}else{
//code...
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
call_method();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
call_method();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
This code works well, but it is very long so I am asking for the best way to write it ?
I want to check firstly if Block node has child equals to my UID if it is true then I want to check if my UID has child equals to specific UID if it is true then I want to get the value of block which is 0 in this example
How can I do that ? Thank you very much.
Just traverse to the path specified using child. You will get no data if the path doesn't exist.
FirebaseDatabase.getInstance().getReference("Block")
.child("MyUUID")
.child("specificUUID")
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
// ... Do something
} else {
call_method();
}
// ... Other code
}
Try this:
Firebaseuser user=FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Block");
ref.child(user.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exist()){
//checks first uid
if(dataSnapshot.hasChild(seconduid){
//checks if seconduid is there
for(DataSnapshot datas:dataSnapshot.getChildren()){
String blocks=datas.child("block").getValue().toString();
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
This will check the first uid if(dataSnapshot.exist()) after that it will check if that uid node has the second uid that you provide if(dataSnapshot.hasChild(seconduid){ then you will iterate and get the node block
I need to find if a child with particular value in one of its fields exists in Firebase.
Below is my database structure:
To check if a field exists,you can do this:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("bdxhATalcDRJCiZZcUFUJo3yrJF2");
ref.addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
//then it exists
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
This will check if
child("bdxhATalcDRJCiZZcUFUJo3yrJF2") exists in the database.
If you do this:
ref=FirebaseDatabase.getInstance().getReference().child("bdxhATalcDRJCiZZcUFUJo3yrJF2").orderByChild("chat_id").equalTo(chatid);
then it will check if that child also exists in the database
In your case you would set up query like this:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.orderByChild("chat_id").equalTo("CHAT_ID_To_COMPARE");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot issue : dataSnapshot.getChildren()) {
// do something with the individual object
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
This would filter your data at server side and no need to filter data at app side.
postRef = FirebaseDatabase.getInstance().getReference().child("bdxhATalcDRJCiZZcUFUJo3yrJF2");
postRef.orderByChild("chat_id").equalTo(chat_id)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
//bus number exists in Database
} else {
//bus number doesn't exists.
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
etEmail is an EditText
I did it for userEmail's value... as I don't have any username other than the email.
for a structure like this...
"users": {
pushId: {
"userEmail": {
}
}
}
onCreate
etEmail.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(final CharSequence s, int start, int before, int count) {
//yourFunction();
DatabaseReference databaseUsers = FirebaseDatabase.getInstance().getReference().child("users");
databaseUsers.orderByChild("userEmail").equalTo(String.valueOf(s))
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot issue : dataSnapshot.getChildren()) {
// do something with the individual object
//User email already exists
//do something
//return; stops the function from executing further
return;
}
} else {
// email doesn't exists.
// do something
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void afterTextChanged(Editable s) {
}
});
When you do the reference and you have your DataSnapshot, you can check it like this:
yourref.child("chat_id").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()) {
//Do something
}
}
exists()
Returns true if the snapshot contains a non-null value.
Also returns true if this DataSnapshot contains any data. It is slightly more efficient than using DataSnapshot.getValue() !== null.
I need to check if conversation child is exist.
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("users").child(senderId);
rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.hasChild("conversations")) {
if (snapshot.child("conversations").hasChild(receiverId)) {
ConversationLocationModel conversationModel = snapshot.child("conversations").child(receiverId).getValue(ConversationLocationModel.class);
roomId = conversationModel.getLocation();
getAllMessage();
} else {
addinLocation();
}
} else {
addinLocation();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
Currently I am using above code to check if child has exist i do not want to check every time so how it can be possible if there is any child exist is there any query for checking child existence.
If you want to check if any child exists, then you can do this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("users").child(senderId).child("conversations");
rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.exists()){
//checks if this snapshots exists
}else{
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
You can change it depending on your database. But the above will check child("users").child(senderId).child("conversations") if conversations exists then it will enter it and see all its children.