Trying To Get Key From a Child Value In Firebase Database - java

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
}

Related

Value of snapshot returns null firebase

I am getting some image ids from firebase but it always returns null even though i am 100% sure data is there and the key names are correct here is my code and firebase database:
String storeidd = getIntent().getStringExtra("storeid");
Query query = FirebaseDatabase.getInstance().getReference().child("Member").child(storeidd).child(childDataSnapshot.getKey()).child("proImages").orderByChild("ImageID").equalTo("1597332319044_0.null");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.exists()){
System.out.println(snapshot.child("ImageID").getValue().toString()); // <- returns null
itemArrayList.add(new ClassListItems(childDataSnapshot.child("proname").getValue().toString(),snapshot.child("ImageID").getValue().toString(),childDataSnapshot.child("proprice").getValue().toString(),childDataSnapshot.child("prodesc").getValue().toString()));
myAppAdapter = new MyAppAdapter(itemArrayList, showProducts.this);
listView21.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView21.setAdapter(myAppAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Also when I print it as System.out.println(snapshot.getValue().toString());
It gives me {-MEcQEJFZCO5Cr0aJSbg={ImageID=1597332319044_0.null}}
Any ideas?
You need to iterate inside the snapshot to be able to get the data:
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.exists()){
for(DataSnapshot ds : snapshot.getChildren()){
String imageID = ds.child("ImageID").getValue(String.class);
}
}
}

How to retrieve this data from firebase database

I want to get to a listview the data on "Categorias" folder, but i try everthing and i can't do this.
Fragment code:
myRef.addValueEventListener(new ValueEventListener() {
public static final String TAG = "TNW";
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
Map<String, Object> td = (HashMap<String,Object>) dataSnapshot.getValue();
list3 values = td.values();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getActivity().getApplicationContext(), "Ese usuario ya existe ", Toast.LENGTH_SHORT).show();
}
});
Its very simple, here is the code to fetch your values.
DatabaseReference db = FirebaseDatabase.getInstance().getReference("people");
db.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds: dataSnapshot.getChildren()){
//get the categorias node
DataSnapshot dsCategorias = ds.child("categorias");
//loop inside the categorias node for all children
for(DataSnapshot dbValSnapshot: dsCategorias.getChildren()){
//Assuming all children have only boolean values
//getting the key and the values
String key = dbValSnapshot.getKey();
boolean value = dbValSnapshot.getValue(Boolean.class);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Let me know if you are not able to understand any part of my code. Thanks

Firebase realtime database - how to get parent name based on a value of one of its keys

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, but I can't

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);

How to get random key from firebase in android?

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();

Categories