Android端Firebase数据注册显示编号而非时间的问题原因排查
问题描述
我不希望Firebase数据注册时出现编号,希望按照代码中设置的currentDateAndTime显示时间节点,请问出现该问题的原因是什么?
相关代码
deviceModels.add(new DeviceModel(newDeviceName, newDeviceWat, newDeviceUse, currentDateAndTime)); FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance(); DatabaseReference databaseReference = firebaseDatabase.getReference(); databaseReference.child("DeviceInfo").child(currentUser).child(currentDateAndTime).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { // data base reference will sends data to firebase. databaseReference.setValue(deviceModels); Toast.makeText(MainActivity.this, "تم أضافة الجهاز", Toast.LENGTH_SHORT).show(); dialog.dismiss(); finish(); startActivity(getIntent()); } });
当前Firebase显示效果

问题原因
- 写入路径错误:你虽然构建了指向
DeviceInfo/{currentUser}/{currentDateAndTime}的引用,但最终调用databaseReference.setValue(deviceModels)时,是把数据写入到数据库的根节点,而非你期望的时间节点路径下。 - List结构自动生成索引:Firebase在接收List类型数据时,会默认给列表中的每个元素分配数字编号作为键,这就是你看到的自动生成的编号。
修复方案
要实现按时间节点存储,需要调整写入目标和数据结构:
方案1:写入单个设备到指定时间节点
直接将单个设备对象写入到DeviceInfo/{currentUser}/{currentDateAndTime}路径下,无需使用List:
// 创建单个设备实例 DeviceModel newDevice = new DeviceModel(newDeviceName, newDeviceWat, newDeviceUse, currentDateAndTime); FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance(); // 明确指定数据写入的目标路径 DatabaseReference targetRef = firebaseDatabase.getReference() .child("DeviceInfo") .child(currentUser) .child(currentDateAndTime); // 写入数据并处理结果 targetRef.setValue(newDevice) .addOnSuccessListener(aVoid -> { Toast.makeText(MainActivity.this, "تم أضافة الجهاز", Toast.LENGTH_SHORT).show(); dialog.dismiss(); finish(); startActivity(getIntent()); }) .addOnFailureListener(e -> { Toast.makeText(MainActivity.this, "أضافة الجهاز فشلت", Toast.LENGTH_SHORT).show(); });
方案2:存储多个设备(时间作为键)
如果需要保存用户的多个设备,保持时间字符串作为每个设备的键,直接写入DeviceInfo/{currentUser}节点下即可,最终数据结构会是:
DeviceInfo └── {currentUser} ├── 2024-05-20 14:30:00 │ ├── name: "设备名称" │ ├── wat: "功率值" │ ├── use: "设备用途" │ └── time: "2024-05-20 14:30:00" └── 2024-05-20 14:35:00 └── ...
内容的提问来源于stack exchange,提问作者Yousef Hashem
相关产品推荐
相关产品推荐

