实时数据库子节点无法显示,因为权限被拒绝。

huangapple go评论57阅读模式
英文:

realtime database child won't showing because permission denied

问题

我想在AddPostActivity中创建名为'Posts'的子项,通过向Firebase添加数据来实现。我的应用程序正常运行,也显示"成功上传",但是在我的数据库中,已经从应用程序输入的数据未被添加。我在创建数据时上传图像,它已成功存储在Firebase存储中,但在实时数据库中,仍然没有显示已添加的数据,即使'Posts'子项本身也没有显示。

我的日志显示以下行。

2023-02-08 12:07:36.353 16589-16674/com.isjieman.ocion W/RepoOperation:/Posts/-NNjQ5njDqkVSZYUIZ-V 失败: 数据库错误拒绝权限
2023-02-08 12:07:41.351 16589-16653/com.isjieman.ocion V/FA: 活动停止断开与服务的连接

这是我的数据库安全规则。

{
  "rules": {
    "User" : {
      "$uid" : {
        ".read" : "$uid === auth.uid",
        ".write" : "$uid === auth.uid",
      }
    }
  }
}

这是数据库结构。

{
  "User": {
    "6FzpJ2sQC9gewbUIGHB8hiNWK1z2": {
      "background_image": "https://firebasestorage.googleapis.com/v0/b/final-project-idn.appspot.com/o/Default%20Images%2Fimg_background.png?alt=media&token=b51e7cf5-2015-4cc4-9583-159373d081e2",
      "bio": "NCT成员",
      "email": "mark@gmail.com",
      "link": "",
      "profile_image": "https://firebasestorage.googleapis.com/v0/b/final-project-idn.appspot.com/o/Profile%20Pictures%2F6FzpJ2sQC9gewbUIGHB8hiNWK1z2.jpg?alt=media&token=17d71d89-353d-44fa-8f06-e33716de0611",
      "uid": "6FzpJ2sQC9gewbUIGHB8hiNWK1z2",
      "userName": "marklee"
    }
  }
}

我认为这是由于我的数据库安全性问题。但我不太清楚如何安全地更改规则。

以下是我的AddPostActivity.kt。

class AddPostActivity : AppCompatActivity(), View.OnClickListener {
    // 以下为你的代码
}
英文:

i want to create child name 'Posts' in addpostactivity by adding data to the firebase. my application running well, it also shows " uploaded successfully ". it just that in my database there's nothing added with the data i already input from my app. i upload image while create the data it's successfully stored in storage firebase, but in realtime database, there's still nothing showing the added data even the 'Posts' child it self

my logchat shows this line.

2023-02-08 12:07:36.353 16589-16674/com.isjieman.ocion W/RepoOperation: updateChildren at /Posts/-NNjQ5njDqkVSZYUIZ-V failed: DatabaseError: Permission denied
2023-02-08 12:07:41.351 16589-16653/com.isjieman.ocion V/FA: Inactivity, disconnecting from the service 

here's my database security rules

{
  "rules": {
    "User" : {
      "$uid" : {
        ".read" : "$uid === auth.uid",
        ".write" : "$uid === auth.uid",
      }
    }
  }
}

and here's the database structure.

{
  "User": {
    "6FzpJ2sQC9gewbUIGHB8hiNWK1z2": {
      "background_image": "https://firebasestorage.googleapis.com/v0/b/final-project-idn.appspot.com/o/Default%20Images%2Fimg_background.png?alt=media&token=b51e7cf5-2015-4cc4-9583-159373d081e2",
      "bio": "Member of NCT",
      "email": "mark@gmail.com",
      "link": "",
      "profile_image": "https://firebasestorage.googleapis.com/v0/b/final-project-idn.appspot.com/o/Profile%20Pictures%2F6FzpJ2sQC9gewbUIGHB8hiNWK1z2.jpg?alt=media&token=17d71d89-353d-44fa-8f06-e33716de0611",
      "uid": "6FzpJ2sQC9gewbUIGHB8hiNWK1z2",
      "userName": "marklee"
    }
  }
}

i think it's because of my database security. but i don't really know about how should i change the rules safely.

here's my AddPostActivity.kt

class AddPostActivity : AppCompatActivity(), View.OnClickListener {
private lateinit var firebaseUser: FirebaseUser
private lateinit var addPostBinding: ActivityAddPostBinding
private var checker = ""
private var myUrl = ""
private var imageUri: Uri? = null
private var storagePostImageRef: StorageReference? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
addPostBinding = ActivityAddPostBinding.inflate(layoutInflater)
setContentView(addPostBinding.root)
supportActionBar?.hide()
//Dropdown item adapter
val itemCategory = listOf("Art", "Writing", "Application", "Design")
val adapterCategory = ArrayAdapter(this, R.layout.item_dropdown, itemCategory)
addPostBinding.acChooseCategory.setAdapter(adapterCategory)
val itemPriceRange = listOf("Rp 0 - 10.000", "Rp 10.000 - 50.000", "Rp 50.000 - 100.000")
val adapterPriceRange = ArrayAdapter(this, R.layout.item_dropdown, itemPriceRange)
addPostBinding.acPriceRange.setAdapter(adapterPriceRange)
firebaseUser = FirebaseAuth.getInstance().currentUser!!
storagePostImageRef = FirebaseStorage.getInstance().reference.child("Posts Pictures")
addPostBinding.btnAddImage.setOnClickListener(this)
addPostBinding.btnSavePost.setOnClickListener(this)
}
override fun onClick(v: View) {
when(v.id){
R.id.btnAddImage -> addImagePost()
R.id.btnSavePost -> savePost()
}
}
private fun savePost() {
if (checker == "clicked")
{
uploadPostWithImage()
}
else
{
uploadPost()
}
}
private fun uploadPost() {
when{
TextUtils.isEmpty(addPostBinding.etTitlePost.text.toString()) -> Toast.makeText(this, "Please add Title Post.", Toast.LENGTH_LONG).show()
TextUtils.isEmpty(addPostBinding.etDescPost.text.toString()) -> Toast.makeText(this, "Please add Description.", Toast.LENGTH_LONG).show()
TextUtils.isEmpty(addPostBinding.acChooseCategory.text.toString()) -> Toast.makeText(this, "Please Choose Category.", Toast.LENGTH_LONG).show()
TextUtils.isEmpty(addPostBinding.acPriceRange.text.toString()) -> Toast.makeText(this, "Please Choose Price Range.", Toast.LENGTH_LONG).show()
TextUtils.isEmpty(addPostBinding.etDurationPost.text.toString()) -> Toast.makeText(this, "Please add Duration Time.", Toast.LENGTH_LONG).show()
TextUtils.isEmpty(addPostBinding.etPaymentMethods.text.toString()) -> Toast.makeText(this, "Please add Payment Methods.", Toast.LENGTH_LONG).show()
else -> {
val ref = FirebaseDatabase.getInstance().reference.child("Posts")
val postId = ref.push().key
val postMap = HashMap<String, Any>()
postMap["postId"] = postId!!
postMap["title"] = addPostBinding.etTitlePost.text.toString()
postMap["description"] = addPostBinding.etDescPost.text.toString()
postMap["category"] = addPostBinding.acChooseCategory.text.toString()
postMap["priceRange"] = addPostBinding.acPriceRange.text.toString()
postMap["duration"] = addPostBinding.etDurationPost.text.toString()
postMap["paymentMethods"] = addPostBinding.etPaymentMethods.text.toString()
postMap["publisher"] = FirebaseAuth.getInstance().currentUser!!.uid
ref.child(postId).updateChildren(postMap)
Toast.makeText(this, "Post Uploaded successfully.", Toast.LENGTH_LONG).show()
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
finish()
}
}
}
private fun uploadPostWithImage() {
when{
imageUri == null -> Toast.makeText(this, "Please select image first.", Toast.LENGTH_LONG).show()
TextUtils.isEmpty(addPostBinding.etTitlePost.text.toString()) -> Toast.makeText(this, "Please add Title Post.", Toast.LENGTH_LONG).show()
TextUtils.isEmpty(addPostBinding.etDescPost.text.toString()) -> Toast.makeText(this, "Please add Description.", Toast.LENGTH_LONG).show()
TextUtils.isEmpty(addPostBinding.acChooseCategory.text.toString()) -> Toast.makeText(this, "Please Choose Category.", Toast.LENGTH_LONG).show()
TextUtils.isEmpty(addPostBinding.acPriceRange.text.toString()) -> Toast.makeText(this, "Please Choose Price Range.", Toast.LENGTH_LONG).show()
TextUtils.isEmpty(addPostBinding.etDurationPost.text.toString()) -> Toast.makeText(this, "Please add Duration Time.", Toast.LENGTH_LONG).show()
TextUtils.isEmpty(addPostBinding.etPaymentMethods.text.toString()) -> Toast.makeText(this, "Please add Payment Methods.", Toast.LENGTH_LONG).show()
else -> {
val progressDialog = ProgressDialog(this)
progressDialog.setTitle("Adding New Post")
progressDialog.setMessage("Please wait, we are Uploading your Post...")
progressDialog.show()
val fileRef = storagePostImageRef!!.child(System.currentTimeMillis().toString() + ".jpg")
val uploadTask: StorageTask<*>
uploadTask = fileRef.putFile(imageUri!!)
uploadTask.continueWithTask(Continuation <UploadTask.TaskSnapshot, Task<Uri>>{ task ->
if (!task.isSuccessful)
{
task.exception?.let {
throw it
progressDialog.dismiss()
}
}
return@Continuation fileRef.downloadUrl
}).addOnCompleteListener (OnCompleteListener<Uri> { task ->
if (task.isSuccessful)
{
val downloadUrl = task.result
myUrl = downloadUrl.toString()
val ref = FirebaseDatabase.getInstance().reference.child("Posts")
val postId = ref.push().key
val postMap = HashMap<String, Any>()
postMap["postId"] = postId!!
postMap["title"] = addPostBinding.etTitlePost.text.toString()
postMap["description"] = addPostBinding.etDescPost.text.toString()
postMap["category"] = addPostBinding.acChooseCategory.text.toString()
postMap["priceRange"] = addPostBinding.acPriceRange.text.toString()
postMap["duration"] = addPostBinding.etDurationPost.text.toString()
postMap["paymentMethods"] = addPostBinding.etPaymentMethods.text.toString()
postMap["post_image"] = myUrl
postMap["publisher"] = FirebaseAuth.getInstance().currentUser!!.uid
ref.child(postId).updateChildren(postMap)
Toast.makeText(this, "Post Uploaded successfully.", Toast.LENGTH_LONG).show()
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
finish()
progressDialog.dismiss()
}
else
{
progressDialog.dismiss()
}
})
}
}
}
private fun addImagePost() {
checker = "clicked"
CropImage.activity()
.setAspectRatio(2, 1)
.start(this)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE  &&  resultCode == Activity.RESULT_OK  &&  data != null)
{
val result = CropImage.getActivityResult(data)
imageUri = result.uri
addPostBinding.btnAddImage.setImageURI(imageUri)
}
}
}

答案1

得分: 1

posts 添加规则。

{
  "rules": {
    "User" : {
      "$uid" : {
        ".read" : "$uid === auth.uid",
        ".write" : "$uid === auth.uid"
      }
    },
    "Posts" : {
      "$uid" : {
        ".read" : "$uid === auth.uid",
        ".write" : "$uid === auth.uid"
      }
    }
  }
}
英文:

Add rules for posts too.

{
"rules": {
"User" : {
"$uid" : {
".read" : "$uid === auth.uid",
".write" : "$uid === auth.uid",
}
}
"Posts" : {
"$uid" : {
".read" : "$uid === auth.uid",
".write" : "$uid === auth.uid",
}
}
}
}

huangapple
  • 本文由 发表于 2023年2月8日 13:20:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75381630.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定