这是android和firebase的新功能,但我需要从firebase实时数据库中获取一些值,类似于sql中的select stmt(从All_machines中选择地址,名称,其中terminal_id =“ terminal_id”)。 当我执行下面的代码时,我得到了一个空指针感知。但是我想还不了解这个概念。
mDatabase = FirebaseDatabase.getInstance().getReference("All Machines");
mDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
try {
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
if (childDataSnapshot.getValue() != null){
try {
if (childDataSnapshot.child("terminal_id").getValue().toString().equals(newTerminal_id)){
String Terminal_address= ""+ childDataSnapshot.child("address").getValue();
String Terminal_name = ""+ childDataSnapshot.child("terminal_name").getValue();
terminal_name.setText(Terminal_name);
terminal_address.setText(Terminal_address);
}
else {
Toast.makeText(getApplicationContext(),"No Entry matching barcode",Toast.LENGTH_LONG).show();
}
//Log.v(TAG,""+ childDataSnapshot.child("terminal_name").getValue()); //gives the value for given keyname
}catch (Exception e){
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(getApplicationContext(),"It's null.",Toast.LENGTH_LONG).show();
}
//Log.v(TAG,""+ childDataSnapshot.getKey()); //displays the key for the node
//get the terminal id for each child then check if it matches the scanned barcode
}
}catch (Exception e){
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
数据库结构:
{
"All Machines": {
"-M-JnXkserObKnDj3iZO": {
"address": "OANDO IDIROKO",
"atmClass": "6627",
"bankName": "SPL",
"brand": "NCR",
"id": "-M-JnXkserObKnDj3iZO",
"ip": "1033944",
"latitude": "10333",
"longitude": "10333",
"serial_no": "13528891",
"terminal_Id": "10332368",
"terminal_name": "ATM9"
}
}
}
答案 0 :(得分:1)
您可以使用orderByChild
和equalTo
方法在服务器端过滤数据,如下所示:
// Get DatabaseReference for All Machines
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("All Machines");
// Use orderByChild to order data by terminal_Id and use equalTo for filter by newTerminal_id
Query query = databaseReference.orderByChild("terminal_Id").equalTo(newTerminal_id);
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
String Terminal_address= childSnapshot.child("address").getValue(String.class);
String Terminal_name = childSnapshot.child("terminal_name").getValue(String.class);
terminal_name.setText(Terminal_name);
terminal_address.setText(Terminal_address);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
输出:如果terminal_Id
等于 10332368 ,则
Terminal_address = "OANDO IDIROKO";
Terminal_name = "ATM9";