My current code is this:
String key = FirebaseDatabase.getInstance().getReference().child("posts").child("???").child("numLikes").toString;
How to get numLikes value?
final ArrayList<Integer> arrayList = new ArrayList<>();
DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference("posts");
dbRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
arrayList.clear();
for (DataSnapshot ds: dataSnapshot.getChildren()) {
int numLike = ds.child("numLikes").getValue(Integer.class);
arrayList.add(numLike);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Try this code, here you don't know pushkey so I have used forEach loop to jump one level down. The arraylist used here will contain all numLikes for your users.
Related
how can filter the value in firebase?
if I want to filter the value in firebase
Because the country values is variable, how can I do?
Below is my code
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts");
Could I filter the values?
Should I
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts").child("country"); //???
=====================Update===================
now, I used this code, but I don't know why I can't get the country value in readPost function. Do I miss something?
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference country_ref = FirebaseDatabase.getInstance().getReference("Users").child(firebaseUser.getUid());
country_ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
country = snapshot.child("country").getValue().toString();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
private void readPosts(){
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading...");
progressDialog.show();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts");
Query query = reference.orderByChild("country").equalTo(country);
query.addListenerForSingleValueEvent(new ValueEventListener() {
I can get the country value in country = snapshot.child("country").getValue().toString();
but can't get in readPost function
Queries in Firebase are done like this:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts")
Query query = reference.orderByChild("country").equalTo("Australia");
You can then read the values matching this query with:
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
Log.d("Firebase", userSnapshot.getKey();
Log.d("Firebase", userSnapshot.child("country").getValue(String.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
})
Also see the Firebase documentation on ordering and filtering data and listening to value events for lists. If you're new to Firebase, I also strongly recommend taking the codelab for Android developers.
To get all countries of "Posts"-
private ArrayList<String> countryNameList;
private String countryName;
private TextView countryNameView;
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Posts");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
countryName = ds.child("country").getValue().toString();
countryNameList.add(countryName);
StringBuilder stringBuilder = new StringBuilder();
for (String s : countryNameList) {
stringBuilder.append(s + "\n");
}
countryNameView.setText(stringBuilder.toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w("TAG", "onCancelled", databaseError.toException());
}
});
I have a database in fire-base. In that I have a child node named "item1", under item1 i have two values
name
prize
I want to retrieve the name of item1 and I want to put it in a string called "foodname". How can I do that?
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("menu");
Here I tried but did not find solution
String foodname; //this string should get the value as "diary milk"
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child("menu").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//This will loop through all items. Add variables to arrays or lists as required
for (DatasnapShot snap : dataSnapshot.getChildren())
{
foodname = dataSnapshot.child("name").getValue().toString();
String prize = dataSnapshot.child("prize").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
You can fetch each child individually like such. Or you can make use of a Model or a Hashmap to fetch all of the data and then fetch the data you would like based on the Key
Using below code you can get food name
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("menu");
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String foodName = snapshot.child("name").getValue().toString();
String foodPrice = snapshot.child("prize").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Retrieving any data from Firebase requires a correct database reference and eventListeners that can work for what you want.
To know more about eventListeners visit this link.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("menu").child("item1");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// this code will get only details from item1
foodname = dataSnapshot.child("name").getValue(String.class);
String price = dataSnapshot.child("prize").getValue(Integer.class);
//if you want details from multiple items, you have to loop over the child nodes like this
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
foodname = snapshot.child("name").getValue().toString();
String price = snapshot.child("prize").getValue().toString();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I want to make a list of dates from the snapshot I get in my firebase database. However when I type the code:
System.out.println(dataSnapshot.getValue());
I get the whole snapshot:
{Date : 2018 - 04 - 11={-L9pZ0HYpBjmvMEL430k={downloadURL="https:...."}
I just want to get a snapshot of the children of dates.
From your snapshot you have to get your child and your element just like this :
private FirebaseDatabase database = FirebaseDatabase.getInstance();
private final DatabaseReference myRef = database.getReference("IndexOfYourDatabse"); //Init your ref at Data
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String date = messageSnapshot.child("date").getValue().toString(); //acces to child => date
System.out.println(date);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
Get date from your object
mDatabaseReference = FirebaseDatabase.getInstance().getReference().child(whatever);
mDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Person person = snapshot.getValue(Person.class);
date = person.getDate();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
This worked for me. Creating a hashmap allowed me to get the key values, which were the dates I needed to put in my listview.
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
HashMap<String, Object> map = (HashMap<String, Object>) dataSnapshot.getValue();
List<String> keys = new ArrayList<>(map.keySet());
for (int i = 0; i < keys.size(); i++) {
System.out.println(keys.get(i));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I have a problem regarding querying the firebase database using a value and getting the specific node. My schema is shown here:
In my schema 'workLocations' belongs to an 'excavationWorks', and 'excavationWorks' belongs to an 'excavationLists'.
That means that the path to a specific workLocation is excavationLists/excavationWorks/workLocations/(specific workLocation)
The problem that I have is that I want to query the workLocations node by the location value (let's say London) and get the parent node (the red circled key which is the key of the specific workLocation).
I have search and read many posts but I haven't managed to make it work.
My code looks like this:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("workLocations").orderByChild("location").equalTo("London");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot workLoc : dataSnapshot.getChildren()) {
// do something with the individual "issues"
Log.d(TAG, workLoc.getKey());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Thank you
To achieve this, you need to query your database twice like this:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
DatabaseReference workLocationsRef = reference
.child("excavationLists")
.child("excavationWorks")
.child("workLocations");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
for(DataSnapshot ds : dSnapshot.getChildren()) {
String key = ds.getKey();
Query query = workLocationsRef.child(key).orderByChild("location").equalTo("London");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
String description = snapshot.child("description").getValue(String.class);
Log.d("description", description);
String partentKey = snapshot.getRef().getParent().getKey();
Log.d("partentKey", partentKey);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
query.addListenerForSingleValueEvent(eventListener);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
workLocationsRef.addListenerForSingleValueEvent(valueEventListener);
A simple question:
Referring to my database image, I want to get the values of the children of node "user" in a list in an Activity, i.e. values "a" and "m" should be displayed in the list.
What should I use and how?
Please try this code:
DatabaseReference yourRef = FirebaseDatabase.getInstance().getReference().child("user");
yourRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> usersList = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String userName = (String) ds.getKey();
usersList.add(userName);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
This is the way in which you'll have in your list, a, m ans so on.
Hope it helps.
You can get the info from the docs here
List<User> allUsers = new ArrayList<>();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("user");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
allUsers.clear();
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
allUsers.add(userSnapshot.getValue(User.class));
}
yourRecyclerViewAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Users failed, log a message
Log.w(TAG, "loadUser:onCancelled", databaseError.toException());
// ...
}
});