gpt4 book ai didi

java - Android Firebase : Hashmap can't be cast to a given Object type

转载 作者:太空宇宙 更新时间:2023-11-04 10:53:04 24 4
gpt4 key购买 nike

我正在尝试查询 Firebase 数据库以检查用户是否存在,以便我可以登录他们。但是,一个奇怪的问题完全阻止了我:

查询代码

String email = emailEditText.getText().toString();
String password = emailEditText.getText().toString();

fbUsers.orderByChild("email").equalTo(email).limitToFirst(1).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
HashMap<String, User> usersHashMap = (HashMap<String, User>) dataSnapshot.getValue();

Map.Entry<String, User> firstEntry = usersHashMap.entrySet().iterator().next();
User foundUser = firstEntry.getValue();

Log.d("Login: ", foundUser.getEmail());
}

@Override
public void onCancelled(DatabaseError databaseError) {

}
});

用户类别

public class User {
private String email;
private String password;

User() {}

public User(String email, String password) {
this.email = email;
this.password = password;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}
}

奇怪的问题是编译器说ALL OK,但是在运行时环境中,这个异常是在Log.d()处抛出的

java.lang.ClassCastException: java.util.HashMap cannot be cast to com.example.project.User

最佳答案

此代码使用 getChildren().iterator().next() 获取单个查询结果的快照。

fbUsers.orderByChild("email")
.equalTo(email).limitToFirst(1)
.addListenerForSingleValueEvent(new ValueEventListener() {

@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterator<DataSnapshot> iter = dataSnapshot.getChildren().iterator();

if (iter.hasNext()) {
User foundUser = iter.next().getValue(User.class);
Log.d("Login: ", foundUser.getEmail());
} else {
Log.w("Login: ", "No match: " + email);
}
}

@Override
public void onCancelled(DatabaseError databaseError) {
if (databaseError != null) {
Log.e("Login: ", "onCancelled: " + databaseError.getMessage());
}
}
});

关于java - Android Firebase : Hashmap can't be cast to a given Object type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47602365/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com