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);
}
}
Related
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) {
}
});
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.
This is my Firebase structure:
"Braccianti" : {
"-KehahFy7z2IrUdchwxk" : {
"Associazione" : "-KehahFy7z4ngUdchwxk",
"Cellulare" : "3402659753",
"Cognome" : "Prova",
"DataDiNascita" : "12/04/1985",
"Nome" : "Bracciante"
},
"ashaosdfao" : {
"Associazione" : "gsdfskjdfsdf",
"Cellulare" : 234235246,
"Cognome" : "Example",
"DataDiNascita" : "10/12/2000",
"Nome" : "exam"
}
"dfsdfsdfsdf" : {
"Associazione" : "ewsvbdtgsdgf",
"Cellulare" : 23523975553,
"Cognome" : "Ex",
"DataDiNascita" : "17/01/1994",
"Nome" : "ghjghj"
}
}
I'd like to get "dfsdfsdfsdf" and "-KehahFy7z2IrUdchwxk" with a single query, so i thought about doing like this:
Query QueryAssociazioni = FirebaseDatabase.getInstance().getReference("Aziende/"+main.getNomeAzienda()+"/Associazioni");
QueryAssociazioni = QueryAssociazioni.equalTo("dfsdfsdfsdf").equalTo("-KehahFy7z2IrUdchwxk");
But it doesn't work.
How can i solve my problem?
Firebase doesn't allow multiple queries, but you can always add a ChildEventListener and check if the child's value :
QueryAssociazioni.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String child = dataSnapshot.getValue().toString();
if(child.equals("dfsdfsdfsdf") || child.equals(("-KehahFy7z2IrUdchwxk"))){
//Do something with the value
}
}
#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) {
}
});
QueryAssociazioni.child("Braccianti")
.orderByChild("Associazione") //key name
.equalTo("Associazione") //value
Try this way...
Thanks.
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) {
}
});
}
This is my data:
{
"users" : {
"00c49c66-7ac8-9a48-7c4541d8bac6" : {
"email" : "d#gmail.com",
"gender" : "m",
"name" : "deepak",
"user_id" : "00c49c66-7ac8-9a48-7c4541d8bac6"
},
"1cb9c1de-1fcf-a2cc-bf78c84e03c8" : {
"email" : "e#gmail.com",
"gender" : "f",
"name" : "ekta",
"user_id" : "1cb9c1de-1fcf-a2cc-bf78c84e03c8"
},
"38211c3f-6c48-8987-0c698b9b9b52" : {
"email" : "c#gmail.com",
"gender" : "m",
"name" : "chirag",
"user_id" : "38211c3f-6c48-8987-0c698b9b9b52"
},
"a536cf1f-419f-9658-cfb5f5a8ec78" : {
"email" : "a#gmail.com",
"gender" : "m",
"name" : "aniket",
"user_id" : "a536cf1f-419f-9658-cfb5f5a8ec78"
},
"c80d828d-48d7-a79a-9cc558cd1960" : {
"email" : "b#gmail.com",
"gender" : "f",
"name" : "bhakti",
"user_id" : "c80d828d-48d7-a79a-9cc558cd1960"
}
}
}
Now I want to get 'name' and 'id' where 'gender' is "m"
Please can anyone tell me how to fire a query like this from Android client to firebase.
I tried tutorials provided by firebase and few other links but didn't got through.
Most of solutions are in Javascript I need it for Android in firebase's java api.
I tried this
public class ActivityHome extends Activity {
String strLoggedInUserID;
TextView tvData;
Firebase fbRef = new Firebase("https://myurl.com/users");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
tvData = (TextView) findViewById(R.id.tvData);
Query queryRef = fbRef.orderByChild("gender").equalTo("m");
Bundle extras = getIntent().getExtras();
strLoggedInUserID = extras.getString("userID");
fbRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
queryRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//long longChildCount = dataSnapshot.getChildrenCount();
// tvData.setText(dataSnapshot).toString();
tvData.setText(s);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
//tvData.setText(s);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
}
Your querying code looks correct, but you're not printing the user.
Since you're adding a ChildEventListener, it will be called for each child:
queryRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//long longChildCount = dataSnapshot.getChildrenCount();
// tvData.setText(dataSnapshot).toString();
tvData.setText(s);
}
The dataSnapshot parameter contains information about a single user. To print their key, name and email:
queryRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
System.out.println(dataSnapshot.key());
System.out.println(dataSnapshot.child("name").getValue());
System.out.println(dataSnapshot.child("email").getValue());
}
Alternatively, you can listen to all children at once with a ValueEventListener.
private static class User {
String email;
String gender;
String name;
#JsonProperty("user_id")
String userId;
public String getEmail() { return email; }
public String getGender() { return gender; }
public String getName() { return name; }
public String getUserId() { return userId; }
}
queryRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
User user = child.getValue(User.class);
System.out.println(user.getEmail());
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
In this last snippet I also use a User class for getting the data from DataSnapshot. As your application grows, this will be more convenient than constantly calling DataSnapshot.child().
This is covered in the section on reading data in the Firebase documentation.