Retrieve all data from Firebase Database - java

ANDROID: I have a Firebase database like this.
In my app, I would like to compile an arraylist that displays all values from the nameofEntry [DESCRIBED BELOW]. By this I mean the "balso," the "nairboh" and so on.
I have the references:
DatabaseReference root = FirebaseDatabase.getInstance().getReference();
DatabaseReference users = root.child("Users");
DatabaseReference childRef = users.child(userID);
DatabaseReference childRefNameNode = childRef.child(nameOfEntry);
childRefNameNode.child(nameOfEntry).setValue(nameOfEntry);
//FETCH DATA
childRefNameNode.child(nameOfEntry).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String valueFromDB = dataSnapshot.getValue(String.class);
Log.i("Jimit", valueFromDB);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
But this only fetches for one entry. How can I get more entries? [All of them]?

You need to use this code snippet. You haven't used any for loop to step over your children.
EDIT: Also, update your database reference as:
//Updated ref
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users").child(userID);*
//add listener to updated ref
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//use the for loop here to step over each child and retrieve data
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()){
String valueFromDB = childSnapshot.getValue(String.class);
Log.i("Jimit", valueFromDB);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Do let me know if it changes anything for you.

Related

Firebase Realtime Database delete item in List

I have the data stored in the Realtime Database in this format:
If I wanted to delete one of the entries in the list named 7P3MRvkC2FQkwcyC7CYVWZP9Ps72, I use this code.
The id under this is generated automatically:
FirebaseDatabase.getInstance()
.getReference()
.child("users")
.child(id) -------------------> unique id
.orderByChild("orderId")
.equalTo(orderId,"orderId")
.getRef()
.removeValue();
But this deletes the complete list of users.
Try this code
DatabaseReference ref = FirebaseDatabase.getInstance()
.getReference()
.child("users")
.child(id);
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
dataSnapshot.getRef().removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
// notify
}
});
}
But this deletes the complete list of users.
That's the expected behavior. If you need to remove only the elements where the orderId property holds the value of a particular "orderId", then you should iterate trough the results like in the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("users");
DatabaseReference uidRef = usersRef.child(uid);
Query query = uidRef.orderByChild("orderId").equalTo(orderId);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
ds.getRef().removeValue();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
query.addListenerForSingleValueEvent(valueEventListener);

To get data of authenticated user failure

public void loadUserInformation() {
final String uid = mAuth.getCurrentUser().getPhoneNumber();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("Users");
// DatabaseReference uidRef = rootRef.child("ref").child(uid);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot: dataSnapshot.getChildren()){
String name=postSnapshot.child("Name").getValue().toString();
// String email=postSnapshot.child("Email").getValue().toString();
Name.setText(name);
// Email.setText(email);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getActivity(),"Error Loading UserDetails",Toast.LENGTH_LONG).show();
}
};
rootRef.addListenerForSingleValueEvent(eventListener);
}
I know why I'm not getting the expected results, its because there's one more child after users. I'm not sure on how to access it, child(uid) gave me a NullPointerException. The present code gives me name of some random user. I want it to return name of the authenticated user i.e. myself
Database - http://ibb.co/iRnF77
Change the phone number to the userid:
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
String userid=user.getUid();
So you will have this database:
Users
userid
Name: namehere
Phone_Number: numberhere
//etc
then you can simply retrieve the data of the current user:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("Users").child(userid);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name=dataSnapshot.child("Name").getValue().toString();
Name.setText(name);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
You don't need the phone number to be the parent node since you already have it as an attribute Phone_Number: number_here, no need to write it twice.
Also getPhoneNumber() can be used if you did phone authentication:
https://firebase.google.com/docs/auth/android/phone-auth

Get specific data from the first item on database

I want to fetch a specific data from Firebase dynamically. This is my structure:
Getting the "Cashier" value of 2 in this image is like this:
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
final DatabaseReference databaseReferenceMyCurrentQueue = firebaseDatabase.getReference("Cashier");
databaseReferenceMyCurrentQueue.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String queuedNumber = String.valueOf(dataSnapshot.getValue());
currentqueue1.setText(queuedNumber);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
How can I make the realtime fetched value of myCurrentQueue from 5 to 6 after deleting the first child of cashier transactions containing the myCurrentQueue of value 5? Thanks in advance.
So every delete, the realtime myCurrentQueue will change as well.
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
final DatabaseReference databaseReferenceMyCurrentQueue = firebaseDatabase.getReference("CashierTransaction");
databaseReferenceMyCurrentQueue.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//get Data as hashMap<String, YourClass>
//then check the lowest number and update the queue
firebaseDatabase.getReference("Cashier").setValue(ThatNumber);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
final DatabaseReference databaseReferenceMyCurrentQueue = firebaseDatabase.getReference("Cashier");
databaseReferenceMyCurrentQueue.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String queuedNumber = String.valueOf(dataSnapshot.getValue());
currentqueue1.setText(queuedNumber);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});

Firebase get the reference of the child of a child

As you see each post has a different Id (the user id who posted) I'm trying to get the reference of this child fx3RqooRMOVRaQHGas4OWQnFK593 for example so the database reference will be like this:
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference().child("Posts").child("fx3RqooRMOVRaQHGas4OWQnFK593");
But what I want is to get that reference dynamically for each post Id.
You have 2 option.
if u want to download one single post then u have to use your custom postId. you can't use pushId(). So that you will know which post u want to download and show.
how to make custom id
FirebaseDatabase.getInstance().getReference().child("Posts")
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
HashMap<String, Object> post = (HashMap<String, Object>) dataSnapshot.getValue();
total= post.size();
}
}
and then create custom id
FirebaseDatabase.getInstance().getReference().child("Posts").child("post"+total).setValue(YourValue);
option 2.
Simply download all post from the post node because u have to ..
FirebaseDatabase.getInstance().getReference().child("Posts")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
//here is your every post
String key = snapshot.getKey();
Object value = snapshot.getValue();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Bonus
if u want to show post of a particular user. (I am assuming that)
u can store the push key inside the user object in a string arrylist. then just call them one by one ...
happy coding :) :)
To achieve this, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference postsRef = rootRef.child("Posts");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String key = ds.getKey();
Log.d("TAG", key);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
postsRef.addListenerForSingleValueEvent(eventListener);
The output will be all those keys.
FirebaseDatabase.getInstance()
.getReference()
.child("Posts")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
String key = snapshot.getKey(); // key here
Object value = snapshot.getValue(); // value here
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Firebase data retrieve with singlechildevent

Here is my firebase data structure . The child "Tags" is a child of root.
final Query searchquery = mDatabase.child("Tags").orderByKey().limitToFirst(10).startAt(s.toString().toLowerCase()).endAt(s.toString().toLowerCase() + "\uf8ff");
searchquery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
String u = dataSnapshot.child("article_name").getValue(String.class);
Toast.makeText(MainActivity.this,":/ : "+u.toString(),Toast.LENGTH_LONG).show();
}catch (Exception tg){
Toast.makeText(MainActivity.this,tg.toString(),Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I want to get the value of child "article_name" . I used the code above . But it is returning null .
Please use this code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference tagsRef = rootRef.child("Tags");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String article_name = ds.child("article_name").getValue(String.class);
Log.d("TAG", tagsRef);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
tagsRef.addListenerForSingleValueEvent(eventListener);
The output will be:
Blood Circulation
Dummy Article
Also don't forget to use names for the keys that does not contain any spaces. So you need to change blood circulation in blood_circulation or bloodCirculation

Categories

Resources