Logcat输出:
java.lang.NullPointerException:尝试调用虚方法' java.lang.String firebase.firebasepractice.User.getUsername()'在null对象引用上。 ......
用户:
MainActivity:
public class MainActivity extends AppCompatActivity {
private EditText name,password;
Button btn;
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText) findViewById(R.id.userName);
password= (EditText) findViewById(R.id.password);
btn= (Button) findViewById(R.id.submit);
tv= (TextView) findViewById(R.id.tv);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DatabaseReference myRef=FirebaseDatabase.getInstance().getReference("Users");
String userId=myRef.push().getKey();
myRef.child(userId).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user=dataSnapshot.getValue(User.class);
tv.setText("Name is "+user.getUsername()+" Email is "+user.getEmail());
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
}
答案 0 :(得分:0)
因为数据快照和用户模型之间的映射失败。
User user=dataSnapshot.getValue(User.class);
// check it null there
if(user != null) {
tv.setText("Name is "+user.getUsername()+" Email is "+user.getEmail());
}
答案 1 :(得分:0)
您在User
类中缺少一个无参数构造函数:
请添加:
public User() {
}
然后,您正在初始化myRef
,如下所示:
myRef=FirebaseDatabase.getInstance().getReference("Users");
然后再次访问“用户”
下的“用户”节点myRef.child("Users")
最后,我相信您将错误的变量传递给.child()
来电:
myRef.child("Users")
.addValueEventListener ...
你应该这样做:
myRef.child(userId) // this line is changed
.addValueEventListener ...
您的最终代码应如下所示:
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference("Users");
String userId = myRef.push().getKey();
myRef.child(userId) // Change: "Users" -> userId
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
tv.setText("Name is " + user.getUsername() + "\tEmail is " + user.getEmail());
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});