You need to enable JavaScript to run this app. Android端Firebase Realtime Database路径失效 数据无法写入问题求解
优惠活动
大模型
产品
解决方案
定价
更多

Android端Firebase Realtime Database路径失效 数据无法写入问题求解

问题背景

正在开发基于Firebase Realtime Database的Android应用,期望实现的数据库树形结构如下:
数据库结构示例图
当前遇到的现象为:应用运行时Logcat无任何错误输出,点击提交按钮后可以正常弹出“Added”的提示Toast,但Firebase Realtime Database中没有实际写入任何数据。

现有代码片段

主页面写入逻辑

public class AddActivity extends AppCompatActivity {

    private EditText etName;
    EditText etRoll;
    Button btnAdmit;
    Button btnView;

    String stName;
    String stRoll;
    FirebaseDatabase myfire;
    DatabaseReference myRef;

    @Override
    public void onBackPressed() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);
        etName = (EditText) findViewById(R.id.idUser);
        etRoll = (EditText) findViewById(R.id.idPass);
        btnView = (Button) findViewById(R.id.idView);

        btnAdmit= (Button) findViewById(R.id.idAdmit);
        myfire = FirebaseDatabase.getInstance();

        myRef = myfire.getReference("Users")
                            .child("uid");// I dont know what
                                          // to write in this child
                                          // in stead of
                                          // "uid"
       

        btnAdmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                stName = etName.getText().toString();
                stRoll = etRoll.getText().toString();


                etName.setText("");
                etRoll.setText("");



                myRef.child("101").addValueEventListener(new ValueEventListener() {

                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                       model model =new basic();
                       model.setFb01name(stName);
                       model.setFb04roll(stRoll);
                       myRef.setValue(model);
                       LayoutInflater inflater = getLayoutInflater();
                       View layout = inflater.inflate(R.layout.toast,
                                (ViewGroup) findViewById(R.id.toast_id));
                       TextView text = (TextView) layout.findViewById(R.id.idToast);
                        text.setText("Added.");
                        Toast toast = new Toast(AddActivity.this);
                        toast.setGravity(Gravity.CENTER ,0, 0);
                        toast.setDuration(Toast.LENGTH_SHORT);
                        toast.setView(layout);
                        toast.show();
                       // btnAdmit.setEnabled(false);
                       // btnAdmit.setVisibility(View.GONE);
                    }




                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) {
                        LayoutInflater inflater = getLayoutInflater();
                        View layout = inflater.inflate(R.layout.toast,
                                (ViewGroup) findViewById(R.id.toast_id));
                        TextView text = (TextView) layout.findViewById(R.id.idToast);
                        text.setText(" Database Error.");
                        Toast toast = new Toast(getApplicationContext());
                        toast.setGravity(Gravity.CENTER ,0, 0);
                        toast.setDuration(Toast.LENGTH_LONG);
                        toast.setView(layout);
                        toast.show();

                        DatabaseError e = null;

                        Log.e("Database", "Error", e.toException());
                    }



                });
            }
        });
}

数据实体类

public class model {

        String fb01name;
        String fb04roll;

        public model() {

        }

        public model(String fb01name, String fb04roll) {
                this.fb01name = fb01name;
                this.fb04roll = fb04roll;
        }



        public String getFb01name() {
                return fb01name;
        }

        public void setFb01name(String fb01name) {
                this.fb01name = fb01name;
        }

        public String getFb04roll() {
                return fb04roll;
        }

        public void setFb04roll(String fb04roll) {
                this.fb04roll = fb04roll;
        }
}

数据库安全规则

{
// Allow anyone to read data, but only authenticated content owners can
// make changes to their data

  "rules": {
    "Users": {
      "$uid": {
        ".read": true,
        // or ".read": "auth.uid != null" for only authenticated users
        ".write": "auth.uid == $uid"
      }
    }
  }
}
问题根因
  • 数据库路径硬编码错误:代码中把动态占位的$uid当成了固定字符串"uid"写在路径里,既没有和规则里的动态用户ID逻辑匹配,也没有通过Firebase Auth拿到当前登录用户的真实UID做路径拼接。
  • 逻辑完全误用ValueEventListener:把写入操作塞在addValueEventListener的onDataChange回调里,这个回调本身是用来监听节点数据变化的——因为你监听的节点初始不存在,会自动触发一次空的回调,直接弹出了“Added”的Toast,但后续的写入操作因为权限问题根本没有执行成功。
  • 权限拦截导致写入静默失败:规则要求Users/{真实用户uid}下的写入必须满足auth.uid == $uid,但代码实际写入的路径是Users/uid,如果当前没有登录Firebase Auth,auth对象为null,完全不满足写入条件。且代码里没有给setValue方法加完成回调,权限拦截的错误不会直接打印在Logcat里,也不会触发onCancelled回调。
  • 类名不匹配的运行时Bug:代码中写了model model =new basic(),但你定义的实体类名是model,不存在basic类,哪怕代码侥幸编译通过,序列化写入的对象结构也是异常的。
修复方案
  1. 修正数据库引用路径:如果已接入Firebase Auth,先获取当前登录用户的真实UID,拼接正确的写入路径:
    // 获取当前登录用户的真实UID
    String currentUid = FirebaseAuth.getInstance().getCurrentUser().getUid();
    // 拼接用户专属路径,替换原来硬编码的"uid"
    myRef = myfire.getReference("Users").child(currentUid);
    
    如果暂时需要测试写入流程,可临时调整安全规则放开测试环境的读写权限:
    {
      "rules": {
        "Users": {
          ".read": true,
          ".write": true
        }
      }
    }
    
  2. 调整写入逻辑:完全移除多余的ValueEventListener监听,直接在按钮点击回调中执行写入,同时给setValue加完成回调捕获真实的写入结果:
    修正后的核心点击逻辑示例:
    btnAdmit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            stName = etName.getText().toString().trim();
            stRoll = etRoll.getText().toString().trim();
            
            // 增加空值校验,避免写入无效内容
            if (TextUtils.isEmpty(stName) || TextUtils.isEmpty(stRoll)) {
                Toast.makeText(AddActivity.this, "请填写完整信息", Toast.LENGTH_SHORT).show();
                return;
            }
            
            etName.setText("");
            etRoll.setText("");
            
            // 修正类名错误,直接构造实体类
            model userInfo = new model(stName, stRoll);
            // 写入并添加完成回调
            myRef.setValue(userInfo, new DatabaseReference.CompletionListener() {
                @Override
                public void onComplete(@Nullable DatabaseError error, @NonNull DatabaseReference ref) {
                    if (error == null) {
                        // 写入成功的Toast逻辑
                        LayoutInflater inflater = getLayoutInflater();
                        View layout = inflater.inflate(R.layout.toast, (ViewGroup) findViewById(R.id.toast_id));
                        TextView text = (TextView) layout.findViewById(R.id.idToast);
                        text.setText("Added.");
                        Toast toast = new Toast(AddActivity.this);
                        toast.setGravity(Gravity.CENTER ,0, 0);
                        toast.setDuration(Toast.LENGTH_SHORT);
                        toast.setView(layout);
                        toast.show();
                    } else {
                        // 捕获真实写入错误,比如权限不足、网络异常
                        Log.e("Database", "写入失败", error.toException());
                        LayoutInflater inflater = getLayoutInflater();
                        View layout = inflater.inflate(R.layout.toast, (ViewGroup) findViewById(R.id.toast_id));
                        TextView text = (TextView) layout.findViewById(R.id.idToast);
                        text.setText("数据库错误:" + error.getMessage());
                        Toast toast = new Toast(getApplicationContext());
                        toast.setGravity(Gravity.CENTER ,0, 0);
                        toast.setDuration(Toast.LENGTH_LONG);
                        toast.setView(layout);
                        toast.show();
                    }
                }
            });
        }
    });
    
  3. 如果需要按学号给每个用户下的子节点做分层存储,直接在用户专属路径下拼接对应子节点即可,比如需要写入Users/{用户真实uid}/101的内容时,引用路径写为:
    myRef = myfire.getReference("Users").child(currentUid).child("101");
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.15 17:54:10