[英]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.