【问题标题】:Associate Firebase Storage with Firebase Realtime Database将 Firebase 存储与 Firebase 实时数据库相关联
【发布时间】:2021-10-30 13:07:31
【问题描述】:

我正在使用 Google Firebase 在 Kotlin 中制作一个标本清点 Android 应用程序。
我使用 firebase Realtime Datebase 来存储标本详细信息并使用 Firebase 存储来存储标本图片。

最终,我希望将所有这些数据提取到应用程序中进行浏览。
我的问题:将实时数据库中的标本详细信息链接到它的相关图片的最佳方法是什么存储?

我的代码

RockEntry.kt

package com.inven.rock_stock

import android.util.Log
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import java.util.*


class RockEntry {
    var name = ""
    var purchDate = ""
    var local = ""
    var mine = ""
    var weight = ""
    var paid = ""
    var asking = ""
    var description = ""
    var dimensions = ""
    var specimenNumber = ""
    var Uid = ""
    var database = FirebaseDatabase.getInstance()
    var ref = database.getReference("Rocks")

    
constructor(name:String,purchDate:String,local:String,mine:String,
                    weight:String,dimensions:String,paid:String,asking:String,
                    description:String,Uid:String){

        this.name = name
        this.purchDate = purchDate.toString()
        this.local = local
        this.mine = mine
        this.weight = weight
        this.dimensions = dimensions
        this.paid = paid
        this.asking = asking
        this.description = description
        this.Uid = UUID.randomUUID().toString()

    }

MainActivity.kt

package com.inven.rock_stock

import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.tasks.Continuation
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageReference
import kotlinx.android.synthetic.main.activity_main.*
import java.io.ByteArrayOutputStream
import java.io.File
import java.net.URI

var CAMERA_REQUEST_CODE = 0
var database = FirebaseDatabase.getInstance()
var ref = database.getReference("Rocks")
private var mStorageRef: StorageReference? = null


class MainActivity : AppCompatActivity() {
    private val TAG = "MyActivity"
    override fun onCreate(savedInstanceState: Bundle?) {
       mStorageRef = FirebaseStorage.getInstance().getReference("ImagesBB")

        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        button.setOnClickListener {
            makeQuery()
        }



        imageBtn.setOnClickListener {
            takePicture()
        }
    }


    private fun makeQuery(){
        var name = name.text.toString()
        var purchDate = purchDate.toString()
        var local = locality.text.toString()
        var mine = mine.text.toString()
        var weight = weight.text.toString()
        var dimensions = dimensions.text.toString()
        var paid = paid.text.toString()
        var asking = asking.text.toString()
        var description = description.text.toString()

        if (!name.isBlank()) {
            ref.child(name.toLowerCase()).setValue(
                RockEntry(
                    name,
                    purchDate,
                    local,
                    mine,
                    weight,
                    paid,
                    asking,
                    dimensions,
                    description
                )
            )
        }

        else {
            Toast.makeText(applicationContext, "Type in a name", Toast.LENGTH_LONG).show()

        }
    }


    private fun takePicture() {
        CAMERA_REQUEST_CODE = 222
        val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        try {
            startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE)
        } catch (e: ActivityNotFoundException) {
            // display error state to the user
        }
    }    

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            CAMERA_REQUEST_CODE -> {
                if (resultCode == Activity.RESULT_OK && data != null) {
                    val imageBitmap = data.extras?.get("data") as Bitmap
                    val baos = ByteArrayOutputStream()
                    imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos)
                    val datar = baos.toByteArray()
                    mStorageRef!!.putBytes(datar)
                    }
                }
            }
        }
    }

【问题讨论】:

    标签: android firebase kotlin firebase-realtime-database backend


    【解决方案1】:

    将 FireBase 存储文件“链接”到您的实时数据库可以通过以下任一方式完成

    1. 获取文件在 FireBase 存储中的位置,通过 存储引用上的 toString()

    2. 通过 .downloadUrl 函数获取可以下载文件的 URL。
      然后,这些选项中的任何一个都可以作为文本存储到实时数据库“条目”中。


      代码示例:

        yourStorageBase?.putFile(element)?.addOnSuccessListener   {
          yourStorageBase?.downloadUrl?.addOnSuccessListener { downloadUri ->
                     // #1 
                     var filepath = yourStorageBase.toString()
                     // #2
                     var downloadLink = downloadUri.toString()                                             
          }
        }
      

    注意: 如果在函数中使用以下代码,您可能会在图片上传完成之前“过早”返回给调用者,这意味着您不能立即使用“链接”。您可以编写一个协程来确保 IO 有时间完成。

    【讨论】:

      【解决方案2】:

      用户 RecyclerView 使用带有数据适配器的实时模型类在您的应用中加载所有数据。

      Firebase 中的用户 DataSnapShot 从父节点获取所有子节点。

      【讨论】:

        【解决方案3】:

        在 Firebase DB 中,您有 specimen 包含许多样本,那么您需要有一个 picture 节点作为每个 specimen 节点的子节点。当您将图片上传到 Firebase Storage 时,获取其 URL 并将其插入到特定样本下的 picture 节点。

        【讨论】:

        • 我认为这是我提出问题的更多地方,谢谢。你有这样的代码示例吗?这个概念是有道理的,但我不知道如何去存储 url 或查询它
        猜你喜欢
        • 2018-10-02
        • 2019-09-06
        • 1970-01-01
        • 2020-10-23
        • 2017-03-04
        • 1970-01-01
        • 1970-01-01
        • 2018-09-17
        • 2020-03-21
        相关资源
        最近更新 更多