Firebase get all key - android

HI everyone I want to catch all the keys on my firebase database:
Users-
26dfg678-
Name: jack
Job: Farmer
43jkhjh4-
Name: bill
Job: ICT
I want to catch the id: 26dfg678 and 43jkhjh4 and put them in an array. This is my code:
final DatabaseReference database_nomi = firebaseDatabase.getReference().child("Users");
database_nomi.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//here
**name[0] = dataSnapshot.getKey();
Provee.setText(name[0]);**
}
#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 i do this it takes only the last but i want all..

To do this you need to read through your Firebase snapshot using a ValueEventListener (and addListenerForSingleValueEvent).
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
int i = 0;
for(DataSnapshot d : dataSnapshot.getChildren()) {
name[i] = d.getKey();
i++;
}
}
}//onDataChange
#Override
public void onCancelled(DatabaseError error) {
}//onCancelled
});
This code uses a foreach to read all dataSnapshot children, saving its key in an array at each iteration.

Related

Query Specific Child Form Firebase

I have the structure in the image below and I want to get the whole data from ALL NODES querying by "amount". How can I do that query? How can I get amount value from all the nodes because all roots are different.
I treid:
zonesRef= FirebaseDatabase.getInstance().getReference("Database");
zone1Ref = zonesRef.child("Payments");
Query queryRef = zone1Ref.orderByChild("amount");
queryRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_SHORT).show();
}
I have differnt users with different UserID. Here is code which i am usign to push data to firebase.
currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser() ;
UserID= currentFirebaseUser.getUid().toString();
zonesRef= FirebaseDatabase.getInstance().getReference("Database");
zone1Ref = zonesRef.child(Type);
zone1NameRef = zone1Ref.child(UserID);
Submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Amount2= Amount.getText().toString();
String Description2= Description.getText().toString().trim();
String uniqueKey = zone1NameRef.push().getKey();
UniqueKey= zone1NameRef.child(uniqueKey);
UniqueKey.child("amount").setValue(Amount2);
UniqueKey.child("date").setValue(currentDateTimeString);
UniqueKey.child("description").setValue(Description2);
UniqueKey.child("school").setValue(School);
}
});
Upon checking your data structure you have two keys before accessing the amount.
DatabaseReference getKeys;
DatabaseReference Amounts;
getKeys = FirebaseDatabase.getInstance().getReference("Database");
Amounts = FirebaseDatabase.getInstance().getReference("Database");
getKeys.child("Payments").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot:dataSnapshot.getChildren()){
String key = snapshot.getKey();
Amounts.child("Payments").child(key).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot1:dataSnapshot.getChildren()) {
String amount = snapshot1.child("amount").getValue(String.class);
Toast.makeText(getApplicationContext(),amount,Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});

How i can find child in Firebase?

I have a structure of Firebase database:
DB
-User
--UID
----UsersMessages
-------uniqueID
-------textMessage
-------typeOfMessage
Code
private void takeDataFromFirebase(){
Query my_message= mRef.child(USERS_CHILD)
.orderByChild(USER_MESSAGES);
my_message.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String
{
}
#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) {
}
});
}
But I need to get all Messages from my users. How can I get those? How I can search only childs "Messages" without "Users" and take "Message text value". Can I? How I can add this information to ListView?
To get all messages across all users, please use the following code:
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
String uid = firebaseUser.getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference messagesRef = rootRef.child(USERS_CHILD).child(uid).child("Messages");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String messageText = ds.child("MessageText").getValue(String.class);
Log.d("TAG", messageText);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
messagesRef.addListenerForSingleValueEvent(eventListener);
Your output will be:
asasddd
asasddd
asasddd
To get the messages from the users, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("Users");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String userKey = ds.getKey();
DatabaseReference messagesRef = usersRef.child(userKey).child("Messages");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
String messageText = dSnapshot.child("MessageText").getValue(String.class);
Log.d("TAG", messageText);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
messagesRef.addListenerForSingleValueEvent(eventListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(valueEventListener);
First, you need to get DatabaseRefence with something like:
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("User/...pathToMessage/Messages");
Then you can load all your messages with a callback:
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
// callback to get all your messages from user.
if (dataSnapshot == null) return;
MessageModel mess = dataSnapshot.getValue(MessageModel.class);
// display message here
}
#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) {
}
});

How to get particular value using `DataSnapshot` in `Firebase`

I want to get particular value using from DataSnapshot.
I am attaching the screenshot here so kindly check and help me to get particular value from Realtime Database.
Actually I am implementing chat application in which I want to get value of user from group_list.
Here is my code.
private void loadTotalGroupList() {
referenceMainUrl = FirebaseDatabase.getInstance().getReferenceFromUrl("https://pure-coda-174710.firebaseio.com");
referenceGroupList = referenceMainUrl.child("group_list");
//Check if child is available or not.
referenceGroupList.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Log.e("dataSnapshot"," ==>"+dataSnapshot);
Map<String, Object> newPost = (Map<String, Object>) dataSnapshot.getValue();
Log.e("newPost"," ==>"+newPost);
Log.e("user: ","==>" + newPost.get("user")); // Here I am getting null value
} else {
Log.e("Child not found", " >>>");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
and log showing like this. DataSnapshot { key = group_list, value = {First Group={-KtBH9gnTszNxcXjNu9A={message=assaasas, user=sakib}}} }
I have resolved my issue by using addChildEventListener
referenceGroupList.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) {
Log.e("dataSnapshot KEY", " ==>" + dataSnapshot.getKey());
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Here dataSnapshot.getKey() returns all sub child of it.
You're listening to the location /group_list in your code. That means a a snapshot from that location will contain the following:
/First Group
/-KtBH9gnTszNxcXjNu9A
message = "..."
user = "..."
If you want to get the user value from that location, you'll have to dig into it using each intermediate path:
dataSnapshot.child("First Group").child("-KtBH9gnTszNxcXjNu9A").child("user").getValue()
Or more simply:
dataSnapshot.child("First Group"/-KtBH9gnTszNxcXjNu9A/user").getValue()
You can't skip the middle paths in the snapshot. Alternatively, you may want to listen to a location closer to the value you want:
referenceMainUrl.child("group_list/First Group/-KtBH9gnTszNxcXjNu9A");
This code runs in a loop and gives you values for all the 'user's
DatabaseReference dRef = FirebaseDatabase.getInstance().getReference().child("group_list").child("First_Group");
dRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
String userName = snapshot.child("user").getValue(String.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

How to fetch the username list in listview in Android from Firebase database?

I have registered and saved users through my app and now I want to fetch the list of usernames as shown below from Firebase database. How do I do it in list view? my database is shown below:
ArrayList<MODELCLASSNAME> Users=new ArrayList<>();
DatabaseReference df=FirebaseDatabase.getInstance().getReference().child("users");
df.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapShot user : dataSnapshot.getchildren()){
Users.add(dataSnapshot.getValue(MODELCLASSNAME.class));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//Now loop through your arraylist
get your database reference
firebaseDatabase = FirebaseDatabase.getInstance();
mPostDb = firebaseDatabase.getReference("User");
Now query your table
Query query = mPostDb.orderByKey();
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapShot user : dataSnapshot){
// Do what ever you whatever you want with this user object
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Try this method:
public void retrieveNames() {
Query myQuery = mDatabase.orderByChild("name").equalTo("INSERT-HERE-A-NAME-FOR-YOUR-SEARCH");
myQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Iterator iterator = dataSnapshot.getChildren().iterator();
//FOR YOUR DATA STRUCTURE -
while (iterator.hasNext()) {
String image_uri = (String) ((DataSnapshot) iterator.next()).getValue();
String name = (String) ((DataSnapshot) iterator.next()).getValue();
String username = (String) ((DataSnapshot) iterator.next()).getValue();
YourUserObject User = new YourUserObject (image_uri, name, username);
YourArrayList.add(User);
}
YourAdapter.notifyDataSetChanged();
}
#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) {
}
});
}

How can i get each child? Firebase getValue [android]

How could i get all the childs from my database?
This code get the first Element, how can i get Element_2,3 and successive? The best i accomplised is serialize the first country and print it.
My Database:
{
"Capitals" : {
"Country_1" : {
"Country" : "Macedonia",
"Capital" : "Skopje"
},
"Country_2" : {
"Country" : "Madagascar",
"Capital" : "Antananarivo"
},
"Country_3" : {
"Country" : "Malawi",
"Capital" : "Lilongwe"
}
}
My Code
#Override
public void onStart(){
super.onStart();
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference capitalsRef = database.getReference("Capitals");
compresoresRef.orderByChild("Ref").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
countryModel cm = dataSnapshot.getValue(countryModel.class);
String country = cm.getCountry();
String capital= cm.getCapital();
textData1.setText(country);
textData2.setText(capital);
}
#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) {
}
});
The dataSnapshot while executing looks like:
DataSnapshot { key =Country_1, value = {Country=Macedonia, Capital=Skopje} }
You should use an ArrayList for store all childs that you get from Firebase using addChildEventListener
ArrayList<countryModel> countryList = new ArrayList<countryModel)();
compresoresRef.orderByChild("Ref").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
countryModel cm = dataSnapshot.getValue(countryModel.class);
countryList.add(cm);
...
}
}
Or if you use addValueEventListener for retrieve data, it will look like
compresoresRef.addValueEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot snapshot) {
countryList.clear();
for (DataSnapshot postSnapshot: snapshot.getChildren()) {
countryModel cm = postSnapshot.getValue(countryModel.class);
countryList.add(cm);
}
}
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
Try this
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
for(DataSnapshot post:dataSnapshot.getChildren())
{
countryModel countryModel cm = post.getValue(countryModel.class);
}
}

Categories

Resources