[英]How get random child from firebase database?
i try to get random child from my firebase.我尝试从我的 firebase 中获取随机孩子。 but i cant, i was try from many idea from stackoverflow too but still not working.但我不能,我也尝试了stackoverflow的许多想法,但仍然无法正常工作。 for example, i want get random child from "Bahan Makanan Susu", and after get a random child i want show the value of "kalori".例如,我想从“Bahan Makanan Susu”中获得随机孩子,在获得随机孩子之后,我想显示“kalori”的值。
This my database created这是我创建的数据库
this my currently code这是我目前的代码
reff = FirebaseDatabase.getInstance().getReference();
reff.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String Sskal =dataSnapshot.child("Bahan Makanan Susu").child("3").child("Kalori").getValue().toString();
'child("3")' in here i create manually and i want to make it random. 'child("3")' 在这里我手动创建,我想让它随机。 thankyou hope u all can help me谢谢你希望你们都可以帮助我
Try this:尝试这个:
reff = FirebaseDatabase.getInstance().getReference("Bahan Makanan Susu/3/Kalori");
reff.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String Sskal = dataSnapshot.getValue().toString();
Log.i("Firebase", Sskal);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
}
The main changes and points to pay attention to:主要变化及注意点:
getReference
.此代码仅从数据库中读取属性,将指向该节点/属性的整个路径传递给getReference
。onCancelled
as it can point out access problems for your database.始终实现onCancelled
,因为它可以指出数据库的访问问题。 If you get an exception for this, search for the error message to learn how to deal with it.如果您遇到此异常,请搜索错误消息以了解如何处理它。google-services.json
file, or specifying the database URL in the getInstance("URL here")
call in your code.如果这也没有读取任何值,您永远无法读取或写入数据库,并且您的数据库位于美国以外的其他区域,请考虑重新下载您的google-services.json
文件,或指定代码中的getInstance("URL here")
调用中的数据库 URL。Try this:尝试这个:
reff = FirebaseDatabase.getInstance().getReference();
reff.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot
dataSnapshot) {
Random r = new Random();
int total = reff.child("Bahan Makanan Susu").getChildrenCount();
String Sskal =dataSnapshot.child("Bahan Makanan
Susu").child(r.nextInt(total)).child("Kalori").getValue().toString(); });苏苏").child(r.nextInt(total)).child("Kalori").getValue().toString(); });
You would have to do a check everytime though so one child doesn't get repeated but I hope you will be able to make it work.你必须每次都做一次检查,这样一个孩子就不会被重复,但我希望你能够让它发挥作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.