Firebase recyclerview 图像在重新加载应用程序后消失

Posted

技术标签:

【中文标题】Firebase recyclerview 图像在重新加载应用程序后消失【英文标题】:Firebase recyclerview images disappear after reload application 【发布时间】:2021-06-17 21:57:29 【问题描述】:

刚添加的时候,一切都很好,但是当我重新启动应用程序时,只显示 textViews。有一个空白空间而不是 imageView。

我的回收适配器:

 class PersonAdapter(options: FirebaseRecyclerOptions<Outfit?>) :
    FirebaseRecyclerAdapter<Outfit, personsViewHolder>(options) 


    override fun onBindViewHolder(holder: personsViewHolder, position: Int, model: Outfit) 
      
        holder.name.text = model.name
        holder.brand.text = model.brand
        holder.size.text = model.size
        holder.comment.text = model.comment
        holder.price.text = model.price
        Picasso.get().load(model.imageUrl).into(holder.imageView) //Glide analog

    

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): personsViewHolder 
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.recycler_item, parent, false)
        return personsViewHolder(view)
    
  
    class personsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) 
        var name: TextView = itemView.findViewById(R.id.tv_name_value)
        var brand: TextView = itemView.findViewById(R.id.tv_brand_value)
        var size: TextView = itemView.findViewById(R.id.tv_size_value)
        var comment: TextView = itemView.findViewById(R.id.tv_comment_value)
        var price: TextView = itemView.findViewById(R.id.tv_price_value)
        var imageView: ImageView = itemView.findViewById(R.id.imageView)

    


类添加到数据库中:

    private var dataBase: DatabaseReference? = null
    private lateinit var outfitImage: ImageView
    private var imageUri: Uri? = null

    private var id: Int = 0

    override fun onCreate(savedInstanceState: Bundle?) 
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_add_outfit)

        nameView = findViewById(R.id.et_outfitName)
        brandView = findViewById(R.id.et_outfitBrand)
        sizeView = findViewById(R.id.et_outfitSize)
        commentView = findViewById(R.id.et_outfitComment)
        priceView = findViewById(R.id.et_outfitPrice)

        btnAdd = findViewById(R.id.btn_addOutfit)
        btnLoad = findViewById(R.id.btn_load)


        btnAdd?.setOnClickListener 
            onClickSave()
            Toast.makeText(this, "Added to database", Toast.LENGTH_SHORT).show()
            startActivity(Intent(this, MainActivity::class.java))
        
        btnLoad?.setOnClickListener 
            onClickRead()
        

        outfitImage = findViewById(R.id.iv_upload_image)
        outfitImage.setOnClickListener 
            chooseImage()
        


    
    //SAVE BUTTON
    private fun onClickSave() 


        dataBase = FirebaseDatabase.getInstance().getReference(UUID.randomUUID().toString())

        dataBase?.setValue(
            Outfit(
                nameView?.text.toString(),
                brandView?.text.toString(),
                sizeView?.text.toString(),
                commentView?.text.toString(),
                priceView?.text.toString(),
                imageUri.toString()
            )
        )
        uploadImageToFirebase(imageUri!!)
    


    //----------------UPLOAD IMAGE-----------------------
    private fun chooseImage() 
        val intent = Intent()
        intent.type = "image/*"
        intent.action = Intent.ACTION_GET_CONTENT
        startActivityForResult(
            Intent.createChooser(intent, "Please select..."), 1
        )
    

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) 
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == 1 && resultCode == Activity.RESULT_OK && data != null && data.data != null) 

            // Get the Uri of data
            imageUri = data.data
            outfitImage.setImageURI(imageUri)
        
    

    private fun uploadImageToFirebase(imageUri: Uri) 

        val pd: ProgressDialog = ProgressDialog(this)
        pd.setTitle("Uploading image...")
        pd.show()

        val fileName = UUID.randomUUID().toString()
        val refStorage = FirebaseStorage.getInstance().reference.child("images/$fileName")

        refStorage.putFile(imageUri)
            .addOnSuccessListener  taskSnapshot ->
                taskSnapshot.storage.downloadUrl.addOnSuccessListener 
                    pd.dismiss()
                    Snackbar.make(
                        findViewById(android.R.id.content),
                        "Image uploaded.",
                        Snackbar.LENGTH_LONG
                    )
                    val imageUrl = it.toString()

                
            

            .addOnFailureListener  e ->
                print(e.message)
                pd.dismiss()
            
            //progressbar
            .addOnProgressListener 
                var progressPercents: Double = (100.00 * it.bytesTransferred / it.totalByteCount)
                pd.setMessage("Percentage: $progressPercents%")
            
    

MainActivity 中的逻辑:

mbase = FirebaseDatabase.getInstance().reference
        recyclerView = findViewById(R.id.recycler1)
        recyclerView.layoutManager = LinearLayoutManager(this)

val options = FirebaseRecyclerOptions.Builder<Outfit>()
            .setQuery(mbase!!, Outfit::class.java)
            .build()
        // Connecting object of required Adapter class to the Adapter class itself
        adapter = PersonAdapter(options)
        // Connecting Adapter class with the Recycler view*/
        recyclerView.adapter = adapter
        swipeRefreshLayout.setOnRefreshListener(this)

以下是后端所有内容的屏幕截图: my backend

images storage

【问题讨论】:

第一次打开应用程序是否有效?对我来说,“content://com.android...”看起来不像一个普通的 URL。 那个链接什么数据库显示给我,像这样:gs://doyouknowkoko-59b8c.appspot.com/images/6bcf6df1-e044-4ec9-8084-8aaf29f7f924 我需要做什么? 您需要使用the download URL。 【参考方案1】:
 private fun uploadToFirebase() 
        val pd: ProgressDialog = ProgressDialog(this)
        pd.setTitle("Uploading image...")
        pd.show()
        val fileName = UUID.randomUUID().toString()
        val refStorage = FirebaseStorage.getInstance().getReference("/images/$fileName")

        refStorage.putFile(selectedPhotoUri!!)
            .addOnSuccessListener 
                    pd.dismiss() //close loading
                    refStorage.downloadUrl.addOnSuccessListener 

                        saveDataToDatabase(it.toString()) //get downloading url
                    
                
            .addOnFailureListener  e ->
                print(e.message)
                pd.dismiss()
            
            //progressbar
            .addOnProgressListener 
                var progressPercents: Double = (100.00 * it.bytesTransferred / it.totalByteCount)
                pd.setMessage("Percentage: $progressPercents%")
            
    

    private fun saveDataToDatabase(imageUrl:String) 
        dataBase = FirebaseDatabase.getInstance().getReference(UUID.randomUUID().toString())

        dataBase?.setValue(
            Outfit(
                nameView?.text.toString(),
                brandView?.text.toString(),
                sizeView?.text.toString(),
                commentView?.text.toString(),
                priceView?.text.toString(),
                imageUrl
            )
        )
    

这是我的解决方案。错误的网址是一个问题。

【讨论】:

以上是关于Firebase recyclerview 图像在重新加载应用程序后消失的主要内容,如果未能解决你的问题,请参考以下文章

来自 Firebase 的 RecyclerView 图像无法加载三个活动中的一个 [重复]

Android:RecyclerView 显示图像 2 次

为什么我在firelerview中显示/不显示我从firebase检索到的图像?

Android:在 Recyclerview 中更改图像旋转

Firebase 图像存储 - 缩略图

recyclerview无法显示图片~