[英]Get value from list of objects Firebase Android Studio
我有以下代码:
public void signOn(String id, String password){
usersReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
boolean valid = false;
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
String key = singleSnapshot.getKey();
if (key.equals(id)) {
singleSnapshot.getValue()//THIS LINE THIS LINE
Intent myIntent = new Intent(WelcomePage.this, MainActivity.class);
myIntent.putExtra("key", key);
WelcomePage.this.startActivity(myIntent);
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
当我调用singleSnapshot.getValue()
时,我得到{password=passwordExample, username=usernameExample}
因为这些是我的实时数据库中的键及其值。 如何访问密码值和用户名值?
一种获取它作为HashMap
并从中提取价值的方法,就像这样。
Map<String, String> map = (Map<String, String>) singleSnapshot.getValue();
String username = (String) map.get("username"); // You should pass exact key names here.
String password = (String) map.get("password");
DataSnapshot#getValue()返回类型为 Object 的object 。 正如 GowthamKK 在他的回答中提到的那样,您确实可以将其转换为 Map<String, Object>,但到目前为止,有一个更简单的解决方案可以根据相应的类型获取值。 所以在代码中,它会很简单:
String password = singleSnapshot.child("password").getValue(String.class);
如您所见,我现在使用了<T> getValue(@NonNull Class<T> valueType
) ,其中:
此方法用于将此快照中包含的数据编组为您选择的 class。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.