在我的Android应用程序中,我想从firebase json对象的所有节点中只检索一个值并检查... 我的firebase数据库看起来像 - >
现在我正在使用此代码来完成我的任务,但每次输出都会变为null ..
public class optChos extends AppCompatActivity {
DatabaseReference ref;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_opt_chos);
final FirebaseDatabase database = FirebaseDatabase.getInstance();
ref = database.getReference("vendorDtl");
}
public void fetchkey(View view) {
EditText etx=findViewById(R.id.etkey);
String keysrch=etx.getText().toString();
Log.i("optionchoose","fetchkeycalled");
Toast.makeText(getApplicationContext(),"Key finfing",Toast.LENGTH_SHORT).show();
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot vst:dataSnapshot.getChildren()) {
vendor vn = vst.getValue(vendor.class);
Toast.makeText(getApplicationContext(), "Email is-> " + vn.getNam(), Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "key is-> " + vn.getVky(), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getApplicationContext(),"nothing fetched",Toast.LENGTH_SHORT).show();
}
});
}
@Override
protected void onStart() {
super.onStart();
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot vst:dataSnapshot.getChildren()) {
vendor vn = vst.getValue(vendor.class);
Toast.makeText(getApplicationContext(), "Email is-> " + vn.getNam(), Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "key is-> " + vn.getVky(), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getApplicationContext(),"nothing fetched",Toast.LENGTH_SHORT).show();
}
});
}
}
此处fetchkey(View view)
是按钮的onclick功能..
我想从每个节点检索
vid
并与用户核实 输入值。我怎么能这样做?
答案 0 :(得分:1)
要从每个节点获取vid
字段的值,请使用以下代码:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference vendorDtlRef = rootRef.child("vendorDtl");
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String vid = ds.child("vid").getValue(String.class);
Log.d("TAG", vid);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
vendorDtlRef.addListenerForSingleValueEvent(eventListener);
答案 1 :(得分:1)
要从每个节点检索vid
,请执行以下操作:
DatabaseReference data = FirebaseDatabase.getInstance().getReference().child("vendorDTl");
data.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot data: dataSnapshot.getChildren()){
String vid=data.child("vid").getValue().toString();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
这将转到数据快照位置vendorDTl
,然后使用该for
循环,它将在该节点的子节点内迭代以获取值vid