I am having trouble fetching the custom push id which is created while pushing the value.
I want to fetch "4wJIGRCkYrZqFpb401hSmgHeBOI3" from rated_user node. Any help will be really useful. Thanks in advance.
Lets say database reference for rated_users is this RatedUser
valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot : dataSnapshot.getChildren()){
String key = postSnapshot.getKey();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
RatedUser.addValueEventListener(valueEventListener);
Use the following code to archive your goal.
private DatabaseReference ref;
ref = FirebaseDatabase.getInstance().getReferenceFromUrl("https://xxxx.firebase.com/rated_users");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
String key = dataSnapshot.getKey();
String value = dataSnapshot.child("key").getValue(String.class);
}catch (Exception e) {
String valws = e.getMessage();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
PS:
I did a quick sample it works for me.
All i did was added a foreach loop:
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
Log.e("children" , snapshot.getKey()+"");
}
this gave me the key "4wJIGRCkYrZqFpb401hSmgHeBOI3"
Related
I have a questions how could i push array list to my freebase data base
and also read it to add a new element , then push it again.
In the above photo you can see i have added array list joinedStudents
and i need to read it and push new elements to it
I've tried the following
DatabaseReference requestsRef = FirebaseDatabase.getInstance().getReference();
requestsRef.child("requests").child(requestID).child("joinedStudents");
requestsRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot d : dataSnapshot.getChildren()) {
String jR = d.getValue(String.class);
joinedStudents.add(jR);
}
joinedStudents.add(studentID);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, "error fetching data from firebase");
}
});
for (String string : joinedStudents) {
requestsRef.child("requests").child(requestID).child("joinedStudents").setValue(string);
}
but it's not working
I believe you have your references slightly mixed up. Try something like:
DatabaseReference joinedStudentsRef = FirebaseDatabase.getInstance().getReference().child("requests").child(requestID).child("joinedStudents");
joinedStudentsRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot d : dataSnapshot.getChildren()) {
String jR = d.getValue(String.class);
joinedStudents.add(jR);
}
joinedStudents.add(studentID);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, "error fetching data from firebase");
}
});
for (String string : joinedStudents) {
joinedStudentsRef.child("1").setValue(string); // setValue is for key, value
// but you have an array
}
Where your reference is now the direct node that you want to monitor/read/write
I am working on an Android application. I want the first child (first UID) of the parent 'support' and store it in a String variable. How do I get the value of the first UID from the list?
I tried one approach. It doesn't work though.
#Override
public void onDataChange(DataSnapshot dataSnapshot1) {
if (dataSnapshot1.exists()) {
String futureUID = "";
for(DataSnapshot futureUIDdatasnapshot:dataSnapshot1.getChildren() ){
futureUID = futureUIDdatasnapshot.getKey();
break;
}
/*Getting the first UID from the list of UID's in queue in 'future'*/
futureUID = dataSnapshot1.getChildren().iterator().next().getKey();
/*Moving a card from 'future' to 'serving'*/
societyServiceUIDReference.child(FIREBASE_CHILD_SERVING).child(futureUID).setValue(FIREBASE_ACCEPTED);
/*Removing the UID from 'future' after it is placed in 'serving'*/
societyServiceUIDReference.child(FIREBASE_CHILD_FUTURE).child(futureUID).removeValue();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
NOTE: 'futureUID' is the UID I want
Try the following:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("support");
Query queryUid=ref.orderByKey().limitToFirst(1);
queryUid.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot datas : dataSnapshot.getChildren()) {
String key=datas.getKey();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Try
DatabaseReference mDatabase;
mDatabase = FirebaseDatabase.getInstance().getReference();
.orderByKey().limitToFirst(n) is what does the trick. It orders the query results by key and returns only the first n results; in this case 1
mDatabase.getChild("support").orderByKey().limitToFirst(1)
.addListenerForSingleValueEvent(new ValueEventListener () {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
for (DataSnapshot supportItem: dataSnapshot.getChildren()) {
String futureUID =supportItem.getKey();
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
//Catch your error here
}
});
see Work with Lists of Data on Android
Hello, I am new to Android development, so I'm hoping for your understanding. I would like to ask how I can retrieve all data under 'values' and get the sum. As you can see, the 'keys' are random-generated keys, which were sent from an Arduino device to Firebase, but the values being sent to Firebase are correct. I want to get the sum and display it on an Android app in a single TextView. I am using Android Studio as IDE for my Android app.
I've tried other snippets from Stack Overflow as well, but it's too confusing for my level of knowledge in Android and I can't make it work. Thank you.
Try like this, may be this will help to achieve your task.
DatabaseReference ref=FirebaseDatabase.getInstance().getReference();
ref.child("data/values").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int toalSum=0;
if (dataSnapshot.getValue() != null) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
//depending upon what datatype youre using caste to it.
totalSum = totalSum+(int)snapshot.getValue();
}
Log.d("LOG","Toatal sum-"+totalSum)
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Try this dataSnapshot.getChildrenCount() will return size
DatabaseReference dbref=FirebaseDatabase.getInstance().getReference();
dbref.child("url/values")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int size = dataSnapshot.getChildrenCount(); //Here u can see the count
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
To count those values, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference valuesRef = rootRef.child("data").child("values");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int sum = o;
for(DataSnapshot ds : dataSnapshot.getChildren()) {
int value = ds.getValue(Integer.class);
sum = sum + value;
}
Log.d("TAG", sum);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
valuesRef.addListenerForSingleValueEvent(eventListener);
Your outout will be:
1780
try this basic split string.
database.geteDatabase().getReference().child("data").child("values")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//dataSnapshot.getValue().toString() = {a=1,b=2,c=3}
String[] value = dataSnapshot.getValue().toString().split("[{,}]");
String[] getA= value[1].split("="); //value[1]='a=1'
String[] getB= value[2].split("="); //value[2]='b=2'
String[] getC= value[3].split("="); //value[3]='c=3'
//what you want to do here.
}
#Override
public void onCancelled(DatabaseError databaseError) { }
});
this can use for other get basic multi value from firebase database.
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());
// ...
}
});
I want to get item in the last node added in firebase database from my Android. You can see on the image below i'm not sure how to get the specific node, because unique key is created by Firebase. How to reference to auto-created node and child inside? Thanks a lot
The last node
Try this:
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
Query lastQuery = databaseReference.child("mp").orderByKey().limitToLast(1);
lastQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String message = dataSnapshot.child("message").getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Handle possible errors.
}
});
Hope this helps!
This might work:
DatabaseReference db = FirebaseDatabase.getInstance().getReference().child("mp");
Query query = db.orderByKey().limitToLast(1);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
Log.d("User key", child.getKey());
Log.d("User val", child.child("message").getValue().toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// TODO: Handle errors.
}
});
I prefer to write and retrieve data through objects.
MyObject is POJO.
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
MyObject myObject = data.getValue(MyObject.class);
Log.i(TAG, data.getKey() + " = " + myObject.toString());
}
}
console.log('last messages', messages[messages.length-1]);