Firebase实时数据库图像未显示在片段Kotlin类中

发布于 2025-02-04 05:14:36 字数 5056 浏览 3 评论 0原文

我正在尝试显示Firebase实时数据库存储中的图像。我以前使用了我的应用程序的以前版本这样做,但是不同之处在于我如何实现它。我的适配器和ArrayList类是完全相同的,而是使用我切换到使用片段的活动。

我的本质上是复制我的旧作品并进行适当的更改,以免遇到错误,但不幸的是我遇到了一些。我来自Firebase的图像根本没有出现,我不确定问题所在。

适配器类

  class AbstractAdapter(private val mContext: Context, private val abstractList: ArrayList<Abstract>) : RecyclerView.Adapter<AbstractAdapter.ViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.abstract_image_view, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        Glide.with(mContext)
            .load(abstractList[position].abstract)
            .into(holder.imageView)
    }

    override fun getItemCount(): Int {
        return abstractList.size
    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var imageView: ImageView = itemView.findViewById(R.id.abstractImageView)

    }

    companion object {
        private const val Tag = "RecyclerView"
    }
}

数据类

    class Abstract {
    var abstract: String? = null

    constructor() {}
    constructor(abstract: String?) {
        this.abstract = abstract
    }
}

片段,其中将显示图像

class AbstractWallpapers: Fragment(), PurchasesUpdatedListener {

private lateinit var subscribeAbstract: Button
private var billingClient: BillingClient? = null

lateinit var recyclerView: RecyclerView
lateinit var abstractlist: ArrayList<Abstract>

private var recyclerAdapterAbstract: AbstractAdapter? = null
private var myRef3: DatabaseReference? = null

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_abstract_wallpaper, container, false)

    recyclerView = requireView().findViewById(R.id.abstract_recyclerView)

}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    recyclerView = view.findViewById(R.id.abstract_recyclerView)

    val layoutManager = LinearLayoutManager(requireActivity())
    recyclerView.layoutManager = layoutManager

    recyclerView.setHasFixedSize(true)

    myRef3 = FirebaseDatabase.getInstance().reference
    abstractlist = ArrayList()

    ClearAll()
    GetDataFromFirebase()

    subscribeAbstract = view.findViewById(R.id.abstract_subscribe_btn)

    subscribeAbstract.setOnClickListener {
        subscribeAbstract()

    }

    // Establish connection to billing client
    //check subscription status from google play store cache
    //to check if item is already Subscribed or subscription is not renewed and cancelled
    billingClient = BillingClient.newBuilder(requireActivity()).enablePendingPurchases().setListener(this).build()
    billingClient!!.startConnection(object : BillingClientStateListener {
        override fun onBillingSetupFinished(billingResult: BillingResult) {
            if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
                val queryPurchase = billingClient!!.queryPurchases(BillingClient.SkuType.SUBS)
                val queryPurchases = queryPurchase.purchasesList
                if (queryPurchases != null && queryPurchases.size > 0) {
                    handlePurchases(queryPurchases)
                } else {
                    saveSubscribeValueToPref(false)
                }
            }
        }

        override fun onBillingServiceDisconnected() {
            Toast.makeText(requireActivity(), "Service Disconnected", Toast.LENGTH_SHORT).show()
        }
    })

    //item subscribed
    if (subscribeValueFromPref) {
        subscribeAbstract.visibility = View.GONE

    } else {
        subscribeAbstract.visibility = View.VISIBLE

    }
}

// Code related to Firebase 
@SuppressLint("NotifyDataSetChanged")
private fun GetDataFromFirebase() {
    val query: Query = myRef3!!.child("Abstract")
    query.addListenerForSingleValueEvent(object : ValueEventListener {
        @SuppressLint("NotifyDataSetChanged")
        override fun onDataChange(snapshot: DataSnapshot) {
            for (dataSnapshot: DataSnapshot in snapshot.children) {
                val abstract = Abstract()

                abstract.abstract = dataSnapshot.child("abstract").value.toString()
                abstractlist.add(abstract)
            }
            recyclerAdapterAbstract = abstractlist.let { AbstractAdapter(requireActivity(), it) }
            recyclerView.adapter = recyclerAdapterAbstract
            recyclerAdapterAbstract!!.notifyDataSetChanged()
        }

        override fun onCancelled(error: DatabaseError) {}
    })
    if (recyclerAdapterAbstract != null) recyclerAdapterAbstract!!.notifyDataSetChanged()
}

private fun ClearAll() {
    abstractlist.clear()
    abstractlist = ArrayList()
}

I'm trying to show images from my Firebase Realtime Database storage. I've done this before with a previous version of my app, but the difference is how I implemented it. My adapter and arraylist class are exactly the same, but instead of using an activity I switched to using fragments.

What I essentially did was copy my old work and make the appropriate changes so I wouldn't run into errors, but unfortunately I ran into some. My images from Firebase are not showing up at all and I'm not sure what is the problem.

Adapter Class

  class AbstractAdapter(private val mContext: Context, private val abstractList: ArrayList<Abstract>) : RecyclerView.Adapter<AbstractAdapter.ViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.abstract_image_view, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        Glide.with(mContext)
            .load(abstractList[position].abstract)
            .into(holder.imageView)
    }

    override fun getItemCount(): Int {
        return abstractList.size
    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var imageView: ImageView = itemView.findViewById(R.id.abstractImageView)

    }

    companion object {
        private const val Tag = "RecyclerView"
    }
}

Data class

    class Abstract {
    var abstract: String? = null

    constructor() {}
    constructor(abstract: String?) {
        this.abstract = abstract
    }
}

Fragment in which images will be shown

class AbstractWallpapers: Fragment(), PurchasesUpdatedListener {

private lateinit var subscribeAbstract: Button
private var billingClient: BillingClient? = null

lateinit var recyclerView: RecyclerView
lateinit var abstractlist: ArrayList<Abstract>

private var recyclerAdapterAbstract: AbstractAdapter? = null
private var myRef3: DatabaseReference? = null

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_abstract_wallpaper, container, false)

    recyclerView = requireView().findViewById(R.id.abstract_recyclerView)

}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    recyclerView = view.findViewById(R.id.abstract_recyclerView)

    val layoutManager = LinearLayoutManager(requireActivity())
    recyclerView.layoutManager = layoutManager

    recyclerView.setHasFixedSize(true)

    myRef3 = FirebaseDatabase.getInstance().reference
    abstractlist = ArrayList()

    ClearAll()
    GetDataFromFirebase()

    subscribeAbstract = view.findViewById(R.id.abstract_subscribe_btn)

    subscribeAbstract.setOnClickListener {
        subscribeAbstract()

    }

    // Establish connection to billing client
    //check subscription status from google play store cache
    //to check if item is already Subscribed or subscription is not renewed and cancelled
    billingClient = BillingClient.newBuilder(requireActivity()).enablePendingPurchases().setListener(this).build()
    billingClient!!.startConnection(object : BillingClientStateListener {
        override fun onBillingSetupFinished(billingResult: BillingResult) {
            if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
                val queryPurchase = billingClient!!.queryPurchases(BillingClient.SkuType.SUBS)
                val queryPurchases = queryPurchase.purchasesList
                if (queryPurchases != null && queryPurchases.size > 0) {
                    handlePurchases(queryPurchases)
                } else {
                    saveSubscribeValueToPref(false)
                }
            }
        }

        override fun onBillingServiceDisconnected() {
            Toast.makeText(requireActivity(), "Service Disconnected", Toast.LENGTH_SHORT).show()
        }
    })

    //item subscribed
    if (subscribeValueFromPref) {
        subscribeAbstract.visibility = View.GONE

    } else {
        subscribeAbstract.visibility = View.VISIBLE

    }
}

// Code related to Firebase 
@SuppressLint("NotifyDataSetChanged")
private fun GetDataFromFirebase() {
    val query: Query = myRef3!!.child("Abstract")
    query.addListenerForSingleValueEvent(object : ValueEventListener {
        @SuppressLint("NotifyDataSetChanged")
        override fun onDataChange(snapshot: DataSnapshot) {
            for (dataSnapshot: DataSnapshot in snapshot.children) {
                val abstract = Abstract()

                abstract.abstract = dataSnapshot.child("abstract").value.toString()
                abstractlist.add(abstract)
            }
            recyclerAdapterAbstract = abstractlist.let { AbstractAdapter(requireActivity(), it) }
            recyclerView.adapter = recyclerAdapterAbstract
            recyclerAdapterAbstract!!.notifyDataSetChanged()
        }

        override fun onCancelled(error: DatabaseError) {}
    })
    if (recyclerAdapterAbstract != null) recyclerAdapterAbstract!!.notifyDataSetChanged()
}

private fun ClearAll() {
    abstractlist.clear()
    abstractlist = ArrayList()
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

嗫嚅 2025-02-11 05:14:36

我解决了我的问题。事实证明,在Firebase实时数据库中,我的规则已将读取的数据库规则设置为false。我的代码非常完美。这只是我的愚蠢错误。

I fixed my problem. It turns out my rules in Firebase Realtime Database rules for read were set to false instead. My code works perfect. It was only a stupid error on my part.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文