You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio中Firebase实时数据库用户资料读取显示问题求助

Firebase实时数据库读取用户数据失败排查

早上好,希望各位一切顺利。

我尝试通过Firebase实时数据库和身份验证,在个人资料页面展示用户数据,但Profile.java代码无法正常运行,以下是相关代码及信息:

注册代码

mAuth.createUserWithEmailAndPassword(email, password)
                    .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            if (task.isSuccessful()) {
                                FirebaseUser user = mAuth.getCurrentUser();
                                Users users = new Users(name, email, password, phonenumber);

                                databaseReference.setValue(users);//.push()
                                
                                startActivity(new Intent(SignUp.this, Home.class));
                                finish();

                            } else {
                                Toast.makeText(SignUp.this, "Register failed.",
                                        Toast.LENGTH_SHORT).show();
                            }
                        }
                    });

个人资料布局(Profile.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:background="@color/white"
    android:layout_height="match_parent"
    tools:context=".Profile">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp">
        <LinearLayout
            android:id="@+id/linear"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:background="@drawable/buttonstyle2"
            android:elevation="5dp"
            android:layout_marginStart="10dp"
            android:layout_marginTop="20dp"
            android:padding="10dp"
            android:layout_marginBottom="10dp"
            android:gravity="center">
            <ImageView
                android:id="@+id/back"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/back"/>


        </LinearLayout>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_toEndOf="@id/linear"
            android:layout_marginTop="26dp"
            android:text="Mon Profile "
            android:textColor="@color/black"
            android:textSize="22sp"
            android:fontFamily="@font/poppins_semibold"
            android:gravity="center"
            />
    </RelativeLayout>

    <TextView
        android:id="@+id/tname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="nom"
        android:fontFamily="@font/poppins_semibold"
        android:textColor="@color/black"
        android:layout_marginStart="30dp"
        android:layout_marginTop="20dp"
        android:textSize="16sp"/>


    <TextView
        android:id="@+id/temail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="email"
        android:fontFamily="@font/poppins_semibold"
        android:textColor="@color/black"
        android:layout_marginStart="30dp"
        android:layout_marginTop="20dp"
        android:textSize="16sp"/>

    <TextView
        android:id="@+id/tphonenumber"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="numéro "
        android:fontFamily="@font/poppins_semibold"
        android:textColor="@color/black"
        android:layout_marginStart="30dp"
        android:layout_marginTop="20dp"
        android:textSize="16sp"/>


    <TextView
        android:id="@+id/tpassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="mot de passe"
        android:fontFamily="@font/poppins_semibold"
        android:textColor="@color/black"
        android:layout_marginStart="30dp"
        android:layout_marginTop="20dp"
        android:textSize="16sp"/>


    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/editProfileButton"
        android:layout_width="match_parent"
        android:layout_marginTop="37dp"
        android:layout_height="50dp"
        android:layout_marginHorizontal="90dp"
        android:layout_marginBottom="30dp"
        android:text="Modifier Profile"
        android:fontFamily="@font/poppins_semibold"
        android:textColor="@color/white"
        android:textAllCaps="false"
        android:textSize="18sp"
        android:textStyle="bold"
        android:background="@drawable/buttonstyle1"/>
</LinearLayout>

Profile.java代码(无法正常运行)

public class Profile extends AppCompatActivity {
    ImageView back;
    AppCompatButton mEditButton;

    private DatabaseReference mDatabase;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_profile);

        back = findViewById(R.id.back);

        // In your onCreate method:
        FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
        mDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUser.getUid());

        mDatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // Get user data from the dataSnapshot
                String email = dataSnapshot.child("email").getValue(String.class);
                String name = dataSnapshot.child("name").getValue(String.class);
                String password = dataSnapshot.child("password").getValue(String.class);
                String phoneNumber = dataSnapshot.child("phonenumber").getValue(String.class);

                // Display user data in profile
                TextView emailTextView = findViewById(R.id.temail);
                emailTextView.setText(email);

                TextView nameTextView = findViewById(R.id.tname);
                nameTextView.setText(name);

                TextView passwordTextView = findViewById(R.id.tpassword);
                passwordTextView.setText(password);

                TextView phoneNumberTextView = findViewById(R.id.tphonenumber);
                phoneNumberTextView.setText(phoneNumber);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.d(TAG, "onCancelled: " + databaseError.getMessage());
            }
        });
    }
}

已附上Firebase实时数据库数据截图与身份验证数据库数据截图,恳请帮忙排查解决,谢谢!


排查方向及解决建议

  • 布局文件引用错误:Profile.java中使用setContentView(R.layout.fragment_profile),但布局文件名是Profile.xml,Android资源文件名需小写,应改为setContentView(R.layout.profile)。
  • 未初始化TAG:Log.d(TAG, ...)中的TAG未定义,需添加private static final String TAG = "ProfileActivity";。
  • 空指针风险:currentUser可能为空,需先判断用户是否已登录:
    FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
    if (currentUser == null) {
        startActivity(new Intent(this, SignUp.class));
        finish();
        return;
    }
    
  • 数据库路径不匹配:检查注册时databaseReference的初始化路径是否为"Users"/currentUser.getUid(),注册代码中需确保路径一致:
    databaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(user.getUid());
    
  • 数据字段名不匹配:检查Users实体类的字段名与数据库中存储的字段名是否完全一致(大小写敏感),比如phonenumber是否和实体类属性名一致。
  • 数据库权限问题:确保Firebase实时数据库规则允许已登录用户读取自身数据,示例规则:
    {
      "rules": {
        "Users": {
          "$uid": {
            ".read": "$uid === auth.uid",
            ".write": "$uid === auth.uid"
          }
        }
      }
    }
    
  • 优化视图初始化:避免在onDataChange中重复调用findViewById,建议在onCreate中提前初始化所有TextView:
    TextView emailTextView, nameTextView, passwordTextView, phoneNumberTextView;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.profile);
    
        // 初始化视图
        back = findViewById(R.id.back);
        emailTextView = findViewById(R.id.temail);
        nameTextView = findViewById(R.id.tname);
        passwordTextView = findViewById(R.id.tpassword);
        phoneNumberTextView = findViewById(R.id.tphonenumber);
    
        // 后续数据库逻辑...
    }
    

内容的提问来源于stack exchange,提问作者Myriam_2189

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 14:37:35