How can I get random key from Firebase realtime database that are stored in list?
Try this:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("inspirational");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String keys=datas.getKey();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
First you need to go the dataSnapshot inspirational, then iterate inside of it and, this will give you the random keys String keys=datas.getKey();
Related
I Have String From Which I am Trying To Get The Key So I Can Use That Key To retrive Some More Value At That Key Location.
This Is My Query Code -
private void xyz()
{
Query t1 = FirebaseDatabase.getInstance().getReference().child("leaderboard").child(matchnumber).child(conlocation).orderByChild("teamname").equalTo(name1);
t1.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String key = dataSnapshot.getKey();
Toast.makeText(Leaderboard.this, key, Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
This is My Database Data Structure.
So I Am Trying To Get The Key 1,2,3,4 But I am Getting Contest1 As a Key.
How about loop through the children:
......
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds: dataSnapshot.getChildren()){
//this runs for every key
String key = ds.getKey();
Toast.makeText(Leaderboard.this, key, Toast.LENGTH_SHORT).show();
}
}
......
For the comment:
.........
for(DataSnapshot ds: dataSnapshot.getChildren()){
//this runs for every key
String key = ds.getKey();
sendKey(key);
........
//new method under your private method
public void sendKey(String key){
//do what ever with the key or keys
}
I am looking for a way to get data from the firebase real-time database in a format like an array[] or a String.
My database looks like this:
Link to image of database
Or:
Database
|
-->Users
|
-->UID1
-->UID2
This is at the root of the database
I want to get a list of all of the UIDs in the "Users" child.
This is the code I have so far and am a bit stuck on:
DatabaseReference databaseReference = firebaseDatabase.getReference("Users");
databaseReference.addValueEventListener(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String UIDs = dataSnapshot.getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I am a bit of a rookie as it comes to java, android studio, and firebase. I am trying to get the data in a format I know how to use like a String or an Array[] of Strings. I looked around if other people had maybe asked the same question, but I could get the answers to those questions to work/didn't understand them.
Thanks in advance for your time!
To get the a list of uids, 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) {
List<String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String uid = ds.getKey();
list.add(uid);
}
//Do what you need to do with your list
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
usersRef.addListenerForSingleValueEvent(valueEventListener);
I recommend you to use the list only inside the callback otherwise it will be empty. If you want to use it outside the onDataChange() method, I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.
For your above question I will give both ways: ArrayList or String with delimiters
ArrayList<String> uids = new ArrayList<String>();
FirebaseDatabase.getInstance().getReference("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
uids.add(snapshot.getKey());
}
}
}
#Override
public void onCancelled(DatabaseError error) {
}
});
For String
String uids = "";
FirebaseDatabase.getInstance().getReference("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
uids += snapshot.getKey() + ",";
}
}
}
#Override
public void onCancelled(DatabaseError error) {
}
});
This gives an output such as: uid1,uid2,uid3,.....uidn,
You can try this:
DatabaseReference ref=
FirebaseDatabase.getInstance().getReference("Users");
ref.addValueEventListener(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
});
name[] is an array of strings!
databaseReference = FirebaseDatabase.getInstance().getReference("/sample");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Log.d(TAG, "onDataChange: dataSnapshot "+dataSnapshot.getValue());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I'm new to android app development and firebase as well. i m fetching data from sample node and getting DataSnapshot value like below.
{size=[Small, Large, Ex-Large], type=[Type 1, Type 2], color=[Red, Green, Blue], category=[T-Shirt, Jeans, Sweater]}
need some expect help, any suggestion will greatly appreciated.
Thanks
To retrieve values separately, you can use a code like this:
databaseReference.child("category").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (int i=0;i<3;i++) {
// category is an ArrayList you can declare above
category.add(dataSnapshot.child(String.valueOf(i)).getValue(String.class));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) { // Do something for this
}
});
Similarly you can add values of other nodes in your other ArrayLists, just by changing the value of Childs in this code.
Firebase has no native support for arrays. If you store an array, it really gets stored as an "object" with integers as the key names.
// we send this
['hello', 'world']
// Firebase stores this
{0: 'hello', 1: 'world'}
Best Practices: Arrays in Firebase
// TRY THIS
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
youNameArray = new ArrayList<>();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
String data = snapshot.getValue(String.class);
youNameArray.add(data);
}
Log.v("asdf", "First data : " + youNameArray.get(0));
}
Something like this:
databaseReference = FirebaseDatabase.getInstance().getReference("/sample");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot sampleSnapshot: dataSnapshot.getChildren()) {
Log.d(TAG, "onDataChange: sampleSnapshot "+sampleSnapshot.getKey()+" = "+sampleSnapshot.getValue());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
The difference is that in my answer I loop over dataSnapshot.getChildren() to get each individual sample snapshot. The sampleSnapshot.getValue() call should return a List.
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference refence = database.getReference();
refence.addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot snapshot) {
// TODO Auto-generated method stub
ArrayList array= new ArrayList<>();
for (DataSnapshot ds : snapshot.getChildren()){
String data = ds.getValue().toString();
array.add(data);
}
System.out.println(array);
}
#Override
public void onCancelled(DatabaseError error) {
// TODO Auto-generated method stub
}
});
In my case String.class does not work instead .toString method works
String data = ds.getValue().toString();
The structure looks like this:
users
|----username1
|----uid:value
username2
|----uid:value
I'm trying to find the best way to get the username value based of the value of it's uid,
This need to be in Java code (Android), So far I found the following code:
Query uid = reference.child("users").orderByChild("uid").equalTo(uid);
uid.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String keys=datas.getKey();
if (keys.equals(uid)) {
// uid found
} else {
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Try this code and create a model class to fetch value of Uid
DatabaseReference users= FirebaseDatabase.getInstance().getReference().child("users");
users.orderByChild("uid").equalTo(uid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot post:dataSnapshot.getChildren()){
//Use a model class to fetch user id like below
UIDDetails u=post.getValue(UIDDetails.class);
String user_id=u.getUid();
//Here all values will be equal to youy required uid if exists more than one
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Please add below code into your file:
DatabaseReference users= FirebaseDatabase.getInstance().getReference().child("users");
final Query userQuery = users.orderByChild("uid");
userQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
map.clear();
if(child.getkey().toString().equalsIgnoreCase(uid)){
//Get the node from the datasnapshot
String myParentNode = dataSnapshot.getKey();
for (DataSnapshot child: dataSnapshot.getChildren())
{
String key = child.getKey().toString();
String value = child.getValue().toString();
map.put(key,value);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
databaseError.toException();
}
});
I want to delete the Firebase database child with this follow code when I click the first item in a list in an app, but I can't. What's wrong?
Query removeCalendar = mCalendarDatabaseReference.limitToFirst(1);
removeCalendar.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String remCal = dataSnapshot.toString();
mCalendarioDatabaseReference.child(remCal).removeValue();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Firebase Queries return a list of possible locations where the query might be satisfied, you'd need to iterate through your dataSnapshot to access those locations. Moreover, this :
String remCal = dataSnapshot.toString();
is not going to print the String value of this snapshot. If you want to get the string value of a dataSnapshot it should be:
String remCal = dataSnapshot.getValue(String.class);
If you want to get the reference of a datasnapshot just use getRef(), you don't have to access the original reference.
Query removeCalendar = mCalendarDatabaseReference.limitToFirst(1);
removeCalendar.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
child.getRef().setValue(null); //deleting the value at this location. You can also use removeValue()
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I solve the problem with this code:
Query removerCalendario = mCalendarioDatabaseReference.limitToFirst(1);
removerCalendario.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
ds.getRef().removeValue();
}
}
You can do mCalendarioDatabaseReference.child(remCal).setValue(null);