如何在Android Studio中用Firebase在TextView展示当前登录用户数据?
嗨,我来帮你搞定这个问题!要在你的用户资料Activity里展示当前登录用户的Firebase实时数据库数据,其实分几步就能搞定,我给你详细拆解下:
首先得确认你已经在项目里集成了Firebase Auth和Firebase实时数据库的依赖,这是前提哈。如果还没配置,记得在app/build.gradle里加上这两个依赖(版本号可以用最新稳定版,下面是当前常用的版本):
implementation 'com.google.firebase:firebase-auth:22.3.1' implementation 'com.google.firebase:firebase-database:20.3.0'
要定位到数据库里对应用户的数据,首先得拿到当前登录用户的唯一标识UID。在你的ProfileActivity里,先获取FirebaseAuth实例并拿到当前用户:
FirebaseAuth mAuth = FirebaseAuth.getInstance(); FirebaseUser currentUser = mAuth.getCurrentUser(); if (currentUser == null) { // 处理用户未登录的情况,比如跳转到登录页 Intent intent = new Intent(this, LoginActivity.class); startActivity(intent); finish(); return; } String userId = currentUser.getUid(); // 这就是数据库中对应用户节点的键
假设你的数据库结构是这样的(应该和你实际的结构匹配):
users
|--- {userId}
|--- name: "张三"
|--- email: "zhangsan@example.com"
|--- phone: "138xxxxxxx"
接下来我们创建数据库引用,添加值事件监听器读取数据并更新TextView:
// 先在onCreate里初始化你的TextView组件 TextView tvName = findViewById(R.id.tv_user_name); TextView tvEmail = findViewById(R.id.tv_user_email); TextView tvPhone = findViewById(R.id.tv_user_phone); // 获取数据库中当前用户节点的引用 DatabaseReference userRef = FirebaseDatabase.getInstance().getReference("users").child(userId); // 创建值事件监听器,读取用户数据 ValueEventListener userListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) { // 方法一:直接读取字段值 String userName = dataSnapshot.child("name").getValue(String.class); String userEmail = dataSnapshot.child("email").getValue(String.class); String userPhone = dataSnapshot.child("phone").getValue(String.class); // 更新UI tvName.setText(userName); tvEmail.setText(userEmail); tvPhone.setText(userPhone); // 方法二:用自定义User类解析(更规范,推荐) // User user = dataSnapshot.getValue(User.class); // tvName.setText(user.getName()); // tvEmail.setText(user.getEmail()); // ... } else { // 数据库中无该用户数据时的提示 tvName.setText("暂无用户资料"); } } @Override public void onCancelled(DatabaseError databaseError) { // 读取失败的处理 Log.w("ProfileActivity", "读取用户资料失败", databaseError.toException()); Toast.makeText(ProfileActivity.this, "加载资料出错", Toast.LENGTH_SHORT).show(); } }; // 添加监听器开始读取数据 userRef.addValueEventListener(userListener);
为了防止内存泄漏,记得在Activity生命周期的onStop方法里移除监听器:
@Override protected void onStop() { super.onStop(); if (userListener != null) { userRef.removeEventListener(userListener); } }
一定要确保Firebase实时数据库的规则允许当前用户读取自己的数据,否则会读取失败!去Firebase控制台的数据库规则页设置为:
{ "rules": { "users": { "$uid": { ".read": "auth != null && auth.uid == $uid", ".write": "auth != null && auth.uid == $uid" } } } }
这个规则的意思是:只有登录用户才能读写自己节点下的数据,既安全又符合需求。
如果用自定义User类解析数据,记得给类添加无参构造函数和getter方法,不然Firebase无法正常解析:
public class User { private String name; private String email; private String phone; // 必须保留无参构造函数 public User() {} public User(String name, String email, String phone) { this.name = name; this.email = email; this.phone = phone; } // 必须添加getter方法 public String getName() { return name; } public String getEmail() { return email; } public String getPhone() { return phone; } }
这样一步步操作下来,就能在你的用户资料Activity里成功展示当前登录用户的数据库数据啦!
内容的提问来源于stack exchange,提问作者Jimbee

