Firebase问题:图片仅传至Storage未同步至Realtime Database求助
Firebase Realtime Database 未同步帖子数据排查
我的应用允许用户上传图片并发布帖子,图片能正常上传到Firebase Storage的Posts Pictures文件夹,但Realtime Database里没有同步description、postImage、publisher、postId这些帖子数据。以下是AddActivity的代码:
class AddActivity : AppCompatActivity() { private var myUrl = "" private var imageUri: Uri? = null private var storagePostPicRef: StorageReference? = null companion object { val pickImage = 100 } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_add) storagePostPicRef = FirebaseStorage.getInstance().reference.child("Posts Pictures") val savePostBtn = findViewById<ImageView>(R.id.save_post_btn) savePostBtn.setOnClickListener { uploadImage() } val gallery = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI) startActivityForResult(gallery, AccountSettingsActivity.pickImage) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) val postpic = findViewById<ImageView>(R.id.image_post) if (resultCode == RESULT_OK && requestCode == AccountSettingsActivity.pickImage) { imageUri = data?.data postpic.setImageURI(imageUri) } } private fun uploadImage() { val descriptionEt = findViewById<EditText>(R.id.location_post) when { imageUri == null -> Toast.makeText(this, "请先选择图片", Toast.LENGTH_LONG).show() TextUtils.isEmpty(descriptionEt.text.toString()) -> Toast.makeText(this, "请填写描述", Toast.LENGTH_LONG).show() else -> { val progressDialog = ProgressDialog(this) progressDialog.setTitle("发布新帖子") progressDialog.setMessage("正在处理,请稍候...") progressDialog.show() val fileRef = storagePostPicRef!!.child(System.currentTimeMillis().toString() + ".jpg") val uploadTask = fileRef.putFile(imageUri!!) uploadTask.continueWithTask(Continuation<UploadTask.TaskSnapshot, Task<Uri>> { task -> if (!task.isSuccessful) { task.exception?.let { progressDialog.dismiss() throw it } } return@Continuation fileRef.downloadUrl }).addOnCompleteListener { task -> progressDialog.dismiss() if (task.isSuccessful) { val downloadUrl = task.result myUrl = downloadUrl.toString() val ref = FirebaseDatabase.getInstance().reference.child("Posts") val postId = ref.push().key ?: run { Toast.makeText(this, "生成帖子ID失败", Toast.LENGTH_SHORT).show() return@addOnCompleteListener } val postMap = hashMapOf( "postid" to postId, "description" to descriptionEt.text.toString().toLowerCase(), "publisher" to FirebaseAuth.getInstance().currentUser?.uid ?: "", "postimage" to myUrl ) // 用setValue创建新节点,而非updateChildren(update需要节点已存在) ref.child(postId).setValue(postMap) .addOnSuccessListener { Toast.makeText(this, "帖子发布成功", Toast.LENGTH_LONG).show() startActivity(Intent(this@AddActivity, MainActivity::class.java)) finish() } .addOnFailureListener { e -> Toast.makeText(this, "发布失败:${e.message}", Toast.LENGTH_LONG).show() } } else { Toast.makeText(this, "获取图片链接失败:${task.exception?.message}", Toast.LENGTH_LONG).show() } } } } } }
核心问题与修复说明
- 节点创建方式错误:原代码使用
updateChildren(postMap),这个方法仅会更新已存在的节点,不会创建新节点。改用setValue(postMap)才能在Realtime Database中创建新的帖子节点。 - 异常处理不完善:
- 原代码中
throw it在progressDialog.dismiss()之前,导致对话框无法关闭,调整顺序确保对话框先消失再抛出异常。 - 添加
addOnSuccessListener和addOnFailureListener监听数据库操作结果,明确告知用户成功/失败原因。
- 原代码中
- 空指针风险规避:对
postId和currentUser?.uid增加非空判断,避免崩溃。 - 请求码统一:建议将启动相册的请求码改为
AddActivity.pickImage,避免依赖其他类的常量,减少耦合。
内容的提问来源于stack exchange,提问作者androidenthusiast
相关产品推荐
相关产品推荐

