[英]How to retrieve data from firebase and setText to a TextView?
I try to retrieve data from firebase and setText to TextViews, but it does not work.我尝试从 firebase 和 setText 检索数据到 TextViews,但它不起作用。 I tried different methods.
我尝试了不同的方法。 I get no error, the strings are not null, but the text does not display.
我没有收到错误,字符串不为空,但文本不显示。 I used these methods and in another projects and they worked.
我在另一个项目中使用了这些方法,它们奏效了。 What am I doing wrong?
我究竟做错了什么?
Here is the code:这是代码:
drawerLayout = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View headerView = navigationView.getHeaderView(0);
navUsername = headerView.findViewById(R.id.navUsername);
navEmail = headerView.findViewById(R.id.navEmail);
ActionBarDrawerToggle toogle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toogle);
toogle.setDrawerIndicatorEnabled(true);
toogle.syncState();
if(savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ArtFragment()).commit();
navigationView.setCheckedItem(R.id.nav_art);
}
auth = FirebaseAuth.getInstance();
currentUser = auth.getCurrentUser();
String uid = currentUser.getUid();
refUsername = FirebaseDatabase.getInstance().getReference().child("users").child(uid);
refUsername.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
User user = dataSnapshot.getValue(User.class);
navUsername.setText(user.getUsername());
navEmail.setText(user.getEmail());
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
Firebase json example: Firebase json 示例:
users
uid
email: ""
password:""
username:""
This is User.class:这是 User.class:
public class User {
String username, email, password;
public User(String username, String email, String password){
this.username = username;
this.email = email;
this.password = password;
}
public User(){}
public void setUsername(){
this.username = username;
}
public String getUsername(){
return username;
}
public void setEmail(){
this.email = email;
}
public String getEmail(){
return email;
}
public void setPassword(){
this.password = password;
}
public String getPassword(){
return password;
}
}
I can see you're trying to fetch data for the local user我可以看到您正在尝试为本地用户获取数据
currentUser = auth.getCurrentUser();
String uid = currentUser.getUid();
refUsername = FirebaseDatabase.getInstance().getReference().child("users").child(uid);
Have you checked from your Firebase database whether that record exists?您是否从 Firebase 数据库中检查过该记录是否存在? You can log the value of the
uid
then check from your Firebase under the users
node您可以记录
uid
的值,然后从users
节点下的 Firebase 检查
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.