首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >NullPointerException:尝试调用虚拟方法& RecyclerView:没有附加适配器;跳过布局,在从Firestore获取数据时出错

NullPointerException:尝试调用虚拟方法& RecyclerView:没有附加适配器;跳过布局,在从Firestore获取数据时出错
EN

Stack Overflow用户
提问于 2021-05-25 14:11:49
回答 2查看 183关注 0票数 0

我试图从Firestore中获取数据并将其显示在RecyclerView中。但是,我得到了以下错误。我在编码方面没有多少经验,但我尝试在我的项目中添加RecyclerViewfragments

我正在使用Kotlin作为语言。

在过去的三天里,我一直在试图找出问题的症结所在和解决办法,但现在我想我必须寻求像你这样的专家的帮助。

下面是我在Logcat中遇到的错误

代码语言:javascript
运行
AI代码解释
复制
16273-16273/com.example.quiz E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.quiz, PID: 16273
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.quiz/com.example.quiz.ui.activities.DashboardActivity}: android.view.InflateException: Binary XML file line #32 in com.example.quiz:layout/activity_dashboard: Binary XML file line #32 in com.example.quiz:layout/activity_dashboard: Error inflating class fragment
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3792)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3968)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2307)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:246)
        at android.app.ActivityThread.main(ActivityThread.java:8512)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
     Caused by: android.view.InflateException: Binary XML file line #32 in com.example.quiz:layout/activity_dashboard: Binary XML file line #32 in com.example.quiz:layout/activity_dashboard: Error inflating class fragment
     Caused by: android.view.InflateException: Binary XML file line #32 in com.example.quiz:layout/activity_dashboard: Error inflating class fragment
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager)' on a null object reference
        at com.example.quiz.ui.fragments.DashboardFragment.onCreateView(DashboardFragment.kt:28)
        at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2963)
        at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:518)
        at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:282)
        at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2189)
        at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:2106)
        at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:2002)
        at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:3138)
        at androidx.fragment.app.FragmentManager.dispatchViewCreated(FragmentManager.java:3065)
        at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:2988)
        at androidx.fragment.app.FragmentStateManager.ensureInflatedView(FragmentStateManager.java:392)
        at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:281)
        at androidx.fragment.app.FragmentLayoutInflaterFactory.onCreateView(FragmentLayoutInflaterFactory.java:140)
        at androidx.fragment.app.FragmentController.onCreateView(FragmentController.java:135)
        at androidx.fragment.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:319)
        at androidx.fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:298)
        at android.view.LayoutInflater.tryCreateView(LayoutInflater.java:1067)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:995)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:959)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:1121)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1082)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:680)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:532)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:479)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:699)
2021-05-27 07:25:09.097 16273-16273/com.example.quiz E/AndroidRuntime:     at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:195)
        at com.example.quiz.ui.activities.DashboardActivity.onCreate(DashboardActivity.kt:15)
        at android.app.Activity.performCreate(Activity.java:8198)
        at android.app.Activity.performCreate(Activity.java:8182)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3765)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3968)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2307)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:246)
        at android.app.ActivityThread.main(ActivityThread.java:8512)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
2021-05-27 07:25:09.166 16273-16273/com.example.quiz I/Process: Sending signal. PID: 16273 SIG: 9

Quiz.kt文件

代码语言:javascript
运行
AI代码解释
复制
package com.example.quiz.models

import android.os.Parcelable
import kotlinx.android.parcel.Parcelize

@Parcelize
data class Quiz(
    val user_id: String = "",
    var quiz_id: String = "",
    val quiz_name: String = "",
    val num_participants: String = "",
    val num_questions: String = "",
    val duration: String = ""

) : Parcelable

DashboardActivity.kt

代码语言:javascript
运行
AI代码解释
复制
package com.example.quiz.ui.activities

import android.os.Bundle
import androidx.core.content.ContextCompat
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.example.quiz.R

class DashboardActivity : BaseActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_dashboard)
        
        supportActionBar!!.setBackgroundDrawable(
            ContextCompat.getDrawable(
                this@DashboardActivity,
                R.drawable.app_gradient_color_background
            )
        )

        val navView: BottomNavigationView = findViewById(R.id.nav_view)

        val navController = findNavController(R.id.nav_host_fragment)
        val appBarConfiguration = AppBarConfiguration(
            setOf(
                R.id.navigation_quizzes,
                R.id.navigation_dashboard
            )
        )
        setupActionBarWithNavController(navController, appBarConfiguration)

        navView.setupWithNavController(navController)
    }

    override fun onBackPressed() {
        doubleBackToExit()
    }
}

DashboardItemListAdapter.kt

代码语言:javascript
运行
AI代码解释
复制
package com.example.quiz.ui.adapters

import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.quiz.R
import com.example.quiz.models.Quiz
import kotlinx.android.synthetic.main.item_list_layout.view.*


open class DashboardItemsListAdapter(
    private val context: Context,
    private var list: ArrayList<Quiz>
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {


    private var onClickListener: OnClickListener? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return MyViewHolder(
            LayoutInflater.from(context).inflate(
                R.layout.item_dashboard_layout,
                parent,
                false
            )
        )
    }


    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val model = list[position]

        if (holder is MyViewHolder) {

            holder.itemView.tv_quiz_name.text = model.quiz_name
            holder.itemView.tv_participants.text = model.num_participants
            holder.itemView.tv_questions.text = model.num_questions
            holder.itemView.tv_duration.text = model.duration

            holder.itemView.setOnClickListener {
                if (onClickListener != null) {
                    onClickListener!!.onClick(position, model)
                }
            }
        }
    }

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


    fun setOnClickListener(onClickListener: OnClickListener) {
        this.onClickListener = onClickListener
    }


    interface OnClickListener {

        fun onClick(position: Int, product: Quiz)
    }


    class MyViewHolder(view: View) : RecyclerView.ViewHolder(view)
}

QuizListAdapter.kt

代码语言:javascript
运行
AI代码解释
复制
package com.example.quiz.ui.adapters

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.quiz.R
import com.example.quiz.models.Quiz
//import com.example.Quiz.utils.GlideLoader
import kotlinx.android.synthetic.main.item_list_layout.view.*

open class QuizListAdapter(
    private val context: Context,
    private val list: ArrayList<Quiz>,
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return MyViewHolder(
            LayoutInflater.from(context).inflate(
                R.layout.item_list_layout,
                parent,
                false
            )
        )
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {

        val model = list[position]

        if (holder is MyViewHolder) {

            holder.itemView.tv_quiz_name.text = model.quiz_name
            holder.itemView.tv_participants.text = model.num_participants
            holder.itemView.tv_questions.text = model.num_questions
            holder.itemView.tv_duration.text = model.duration

        }

    }

    override fun getItemCount(): Int {

        return list.size
    }

    class MyViewHolder(view: View) : RecyclerView.ViewHolder(view)
}

DashboardFragment.kt

代码语言:javascript
运行
AI代码解释
复制
package com.example.quiz.ui.fragments

import android.os.Bundle
import android.util.Log
import android.view.*
import androidx.recyclerview.widget.GridLayoutManager
import com.example.quiz.R
import com.example.quiz.firestore.FirestoreClass
import com.example.quiz.models.Quiz
import com.example.quiz.ui.adapters.DashboardItemsListAdapter
import kotlinx.android.synthetic.main.fragment_dashboard.*

class DashboardFragment : BaseFragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setHasOptionsMenu(true)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        return inflater.inflate(R.layout.fragment_dashboard, container, false)
    }

    override fun onResume() {
        super.onResume()

        getDashboardItemsList()
    }

    private fun getDashboardItemsList() {
        showProgressDialog("please_wait")

        FirestoreClass().getDashboardItemsList(this@DashboardFragment)
    }

    fun successDashboardItemsList(dashboardItemsList: ArrayList<Quiz>) {

        hideProgressDialog()

        for (i in dashboardItemsList) {
            Log.i("Item Title", i.quiz_name)
        }

        if (dashboardItemsList.size > 0) {

            rv_dashboard_items.visibility = View.VISIBLE
            tv_no_dashboard_items_found.visibility = View.GONE

            rv_dashboard_items.layoutManager = GridLayoutManager(activity, 1)
            rv_dashboard_items.setHasFixedSize(true)

            val adapter = DashboardItemsListAdapter(requireActivity(), dashboardItemsList)
            rv_dashboard_items.adapter = adapter

        } else {
            rv_dashboard_items.visibility = View.GONE
            tv_no_dashboard_items_found.visibility = View.VISIBLE
        }
    }
}

使用上面的代码,我的应用程序在输入用户名和密码后会崩溃,但是当我删除rv_dashboard_items.adapter = adapter时,应用程序至少不会崩溃。但是,它根本不显示来自Firestore的任何数据。

在不使用rv_dashboard_items.adapter = adapter的情况下运行应用程序时会出现以下错误

以下片段中的消息是红色的。

代码语言:javascript
运行
AI代码解释
复制
E/DashboardFragment: [DocumentSnapshot{key=quizzes/C8STnkYwp3cYWMxm1Y0xQWERTZq1, metadata=SnapshotMetadata{hasPendingWrites=false, isFromCache=false}, doc=Document{key=quizzes/C8STnkYwp3cYWMxm1Y0xQWERTZq1, version=SnapshotVersion(seconds=1621955183, nanos=678854000), type=FOUND_DOCUMENT, documentState=SYNCED, value=ObjectValue{internalValue=# com.google.firestore.v1.Value@1abc2d14
integer_value: 0
map_value {
  fields {
    key: "quiz_id"
    value {
      integer_value: 0
      string_value: "C8STnkYwp3cYWMxm1Y0xQWERTZq1"
    }
  }
  fields {
    key: "num_questions"
    value {
      integer_value: 0
      string_value: "10"
    }
  }
  fields {
    key: "quiz_name"
    value {
      integer_value: 0
      string_value: "Easy Quiz"
    }
  }
  fields {
    key: "duration"
    value {
      integer_value: 0
      string_value: "10"
    }
  }
  fields {
    key: "num_participants"
    value {
      integer_value: 0
      string_value: "5"
    }
  }
  fields {
    key: "user_id"
    value {
      integer_value: 0
      string_value: "C8STnkYwp3cYWMxm1Y0xQWERTZq1"
    }
  }
}}}}]

还有这条线

代码语言:javascript
运行
AI代码解释
复制
E/RecyclerView: No adapter attached; skipping layout

QuizFragment.kt

代码语言:javascript
运行
AI代码解释
复制
package com.example.quiz.ui.fragments

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.quiz.R
import com.example.quiz.firestore.FirestoreClass
import com.example.quiz.models.Quiz
import com.example.quiz.ui.adapters.QuizListAdapter
import kotlinx.android.synthetic.main.fragment_quiz.*

class QuizFragment : BaseFragment() {

    private lateinit var mRootView: View


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

    fun successQuizListFromFireStore(quizList: ArrayList<Quiz>) {

        hideProgressDialog()

        if (quizList.size > 0) {
            rvQuizzesFrag.visibility = View.VISIBLE
            tv_no_products_found.visibility = View.GONE

            rvQuizzesFrag.layoutManager = LinearLayoutManager(activity)
            rvQuizzesFrag.setHasFixedSize(true)
            val adapterQuizzes = QuizListAdapter(requireActivity(), quizList)
            rvQuizzesFrag.adapter = adapterQuizzes

        } else {
            rvQuizzesFrag.visibility = View.GONE
            tv_no_products_found.visibility = View.VISIBLE
        }
    }


    private fun getQuizListFromFireStore() {

        showProgressDialog("Please_wait")
        FirestoreClass().getQuizList(this)
    }

    override fun onResume() {
        super.onResume()
        getQuizListFromFireStore()
    }
}

activity_dashboard.xml

代码语言:javascript
运行
AI代码解释
复制
    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        android:background="@drawable/app_gradient_color_background"
        app:itemIconTint="@color/colorWhite"
        app:itemTextColor="@color/colorWhite"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@id/nav_view"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/mobile_navigation" />


</androidx.constraintlayout.widget.ConstraintLayout>

fragment_dashboard.xml

代码语言:javascript
运行
AI代码解释
复制
    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    tools:context=".ui.fragments.DashboardFragment">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv_dashboard_items"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/tv_no_dashboard_items_found"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:text="no_dashboard_item_found"
        android:textAlignment="center"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

fragment_quiz.xml

代码语言:javascript
运行
AI代码解释
复制
    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.fragments.QuizFragment">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rvQuizzesFrag"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/tv_no_products_found"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:text="NO QUIZZES TODAY"
        android:textAlignment="center"
        android:textSize="30sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

FirestoreClass.kt

当我超过问题中的字符限制时,代码的Import部分将从问题中删除。

代码语言:javascript
运行
AI代码解释
复制
package com.example.quiz.firestore


class FirestoreClass {

    private val mFireStore = FirebaseFirestore.getInstance()

    fun getDashboardItemsList(fragment: DashboardFragment) {
       
        mFireStore.collection("quizzes")
            .get() 
            .addOnSuccessListener { document ->

                Log.e(fragment.javaClass.simpleName, document.documents.toString())

                val quizList: ArrayList<Quiz> = ArrayList()

               
                for (i in document.documents) {

                    val qz = i.toObject(Quiz::class.java)!!
                    qz.quiz_id = i.id
                    quizList.add(qz)
                }

                fragment.successDashboardItemsList(quizList)
            }
            .addOnFailureListener { e ->
              
                fragment.hideProgressDialog()
                Log.e(fragment.javaClass.simpleName, "Error while getting dashboard items list.", e)
            }
    }


    fun getCurrentUserID(): String {
        // An Instance of currentUser using FirebaseAuth
        val currentUser = FirebaseAuth.getInstance().currentUser

        var currentUserID = ""
        if (currentUser != null) {
            currentUserID = currentUser.uid
        }

        return currentUserID
    }


    fun uploadProductDetails(activity: AddProductActivity, productInfo: Quiz) {

        mFireStore.collection("quizzes")
            .document()
          
            .set(productInfo, SetOptions.merge())
            .addOnSuccessListener {

              
                activity.productUploadSuccess()
            }
            .addOnFailureListener { e ->

                activity.hideProgressDialog()

                Log.e(
                    activity.javaClass.simpleName,
                    "Error while uploading the product details.",
                    e
                )
            }
    }

    fun getUserDetails(activity: Activity) {

        mFireStore.collection("users")
         
            .document(getCurrentUserID())
            .get()
            .addOnSuccessListener { document ->

                Log.i(activity.javaClass.simpleName, document.toString())

                val user = document.toObject(User::class.java)!!

                val sharedPreferences =
                    activity.getSharedPreferences(
                        Constants.MYAPP_PREFERENCES,
                        Context.MODE_PRIVATE
                    )

                val editor: SharedPreferences.Editor = sharedPreferences.edit()
                editor.putString(
                    Constants.LOGGED_IN_USERNAME,
                    "${user.firstName} ${user.lastName}"
                )
                editor.apply()

                when (activity) {
                    is LoginActivity -> {
                      
                        activity.userLoggedInSuccess(user)
                    }

                }
            }
            .addOnFailureListener { e ->
               
                when (activity) {
                    is LoginActivity -> {
                        activity.hideProgressDialog()
                    }
                }

                Log.e(
                    activity.javaClass.simpleName,
                    "Error while getting user details.",
                    e
                )
            }
    }


    fun getQuizList(fragment: Fragment) {
      
        mFireStore.collection("quizzes")
            .whereEqualTo("user_id", getCurrentUserID())
            .get() 
            .addOnSuccessListener { document ->

                Log.e("Products List", document.documents.toString())

                val productsList: ArrayList<Quiz> = ArrayList()

                for (i in document.documents) {

                    val product = i.toObject(Quiz::class.java)
                    product!!.quiz_id = i.id

                    productsList.add(product)
                }

                when (fragment) {
                    is QuizFragment -> {
                        fragment.successQuizListFromFireStore(productsList)
                    }
                }
            }
            .addOnFailureListener { e ->
               
                when (fragment) {
                    is QuizFragment -> {
                        fragment.hideProgressDialog()
                    }
                }

                Log.e("Get Product List", "Error while getting product list.", e)
            }
    }


    fun getAllQuizList(activity: Activity) {
       
        mFireStore.collection("quizzes")
            .get() 
            .addOnSuccessListener { document ->

                Log.e("Products List", document.documents.toString())

                val productsList: ArrayList<Quiz> = ArrayList()

                for (i in document.documents) {

                    val product = i.toObject(Quiz::class.java)
                    product!!.quiz_id = i.id

                    productsList.add(product)
                }

            }
            .addOnFailureListener { e ->
                Log.e("Get Product List", "Error while getting all product list.", e)
            }
    }

}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-05-25 18:02:11

在阅读了您的代码之后,我认为原因是:在使用recycleView时可能会出现一些小问题。

在您的代码中,您似乎在xml的同一个位置使用了两个xml,一个是没有数据的recycleView,另一个是异步获取数据后的recycleView。然后在获取数据的功能中控制recycleView的显示和隐藏。

但是,如果在将回收视图附加到片段后不立即初始化它,您可能会看到No adapter attached; skipping layout

解决方案:只需设置一个recycleView,并在片段/活动的初始化函数中为其设置一个空数据。DashboardItemsListAdapter(requireActivity(), listOf<Quiz>())

守则的一部分:

代码语言:javascript
运行
AI代码解释
复制
private lateinit var adapter: DashboardItemsListAdapter

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    adapter = DashboardItemsListAdapter(requestActivity(), arrayListOf<Quiz>())
}

fun successDashboardItemsList(dashboardItemsList: ArrayList<Quiz>) {
    adapter.list = dashboardItemsList
    adapter.notifyDataSetChanged()
}

我只是在这里提供我的一个想法。您不能每次调用successDashboardItemsList()时都设置一个新适配器。在调用successDashboardItemsList()之前,应该初始化适配器(可能没有数据)。每次调用successDashboardItemsList()时,重新分配Adapter对象的list字段的值。并调用Adapter对象的notifyDataSetChanged(),以便解决问题。

代码语言:javascript
运行
AI代码解释
复制
import android.os.Bundle
import android.util.Log
import android.view.*
import androidx.recyclerview.widget.GridLayoutManager
import com.example.quiz.R
import com.example.quiz.firestore.FirestoreClass
import com.example.quiz.models.Quiz
import com.example.quiz.ui.adapters.DashboardItemsListAdapter
import kotlinx.android.synthetic.main.fragment_dashboard.*

class DashboardFragment : BaseFragment() {

    private lateinit var adapter: DashboardItemsListAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setHasOptionsMenu(true)
    }

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



    private lateinit var recyclerView: RecyclerView

    private lateinit var textView: TextView

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        recyclerView = view.findViewById<RecyclerView>(R.id.rv_dashboard_items)
        textView = view.findViewById(R.id.tv_no_dashboard_items_found)
        adapter = DashboardItemsListAdapter(requireActivity(), arrayListOf<Quiz>())
        recyclerView.layoutManager = GridLayoutManager(requireContext(), 1)
        recyclerView.setHasFixedSize(true)
        recyclerView.adapter = adapter
    }

    override fun onResume() {
        super.onResume()

        getDashboardItemsList()
    }

    private fun getDashboardItemsList() {
        showProgressDialog("please_wait")

        FirestoreClass().getDashboardItemsList(this@DashboardFragment)
    }

    fun successDashboardItemsList(dashboardItemsList: ArrayList<Quiz>) {

        hideProgressDialog()

        for (i in dashboardItemsList) {
            Log.i("Item Title", i.quiz_name)
        }

        if (dashboardItemsList.size > 0) {

            recyclerView.visibility = View.VISIBLE
            textView.visibility = View.GONE

            adapter.list = dashboardItemsList
            adapter.notifyDataSetChanged()
        } else {
            recyclerView.visibility = View.GONE
            textView.visibility = View.VISIBLE
        }
    }
}

DashboardItemListAdapter.kt

改为:

代码语言:javascript
运行
AI代码解释
复制
  override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
         return MyViewHolder(
             LayoutInflater.from(context).inflate(
                 R.layout.item_list_layout,
                 parent,
                 false
             )
         )
     }
票数 1
EN

Stack Overflow用户

发布于 2021-05-26 02:45:25

在您的DashboardItemsListAdapter中,您正在膨胀item_dashboard_layout,但是您正在为fragment_dashboard导入合成绑定。

膨胀的布局可能不包含fragment_dashboard绑定所需的视图,因此绑定返回空值。

确保在充气和视图绑定中使用相同的布局。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67696197

复制
相关文章
jsonobject string转json_string转换为long
本文使用一个小例子展示在java中怎样将一个JSON格式的字符串转化为JSONObject对象。注意,我们使用的是 org.json.simple.JSONObject;
全栈程序员站长
2022/09/22
3.4K0
jsonobject string转json_string转换为long
integer转string java_Integer转换为String类型[通俗易懂]
Exception in thread “main” java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
全栈程序员站长
2022/11/01
2.1K0
string转换为jsonarray_jsonobject转jsonarray
如果用的是fastjson 则导包为 import com.alibaba.fastjson.JSONObject
全栈程序员站长
2022/09/22
2K0
string转换为jsonarray_jsonobject转jsonarray
java map 转string_java-将Map <String,Object>转换为Map <String,String>
Map map = new HashMap(); //Object is containing String
全栈程序员站长
2022/08/25
12.4K0
integer转换为string_go 字符串转int
str := “123” // string 转 int i, err := strconv.Atoi(str) if err == nil {   fmt.Printf(“i: %v\n”,i) } // string 转 int64 i64,err := strconv.ParseInt(str,10,64) if err == nil {   fmt.Printf(“i64: %v\n”,i64) } // string 转 int32 j,err := strconv.ParseInt(str,10,32) if err == nil {   fmt.Printf(“i32: %v\n”,int32(j)) }
全栈程序员站长
2022/11/06
3.5K0
PHP中的Array2String & String2Array
在用PHP开发时我们有时期望将一个数组(任意多维),在页面之间传递或者存入数据库。这时我们可以将Array转换为String传递或保存,取出用的时候在转换回来即可。 <?/*在Array和String
joshua317
2018/04/10
2K0
java把string转int类型_java把String类型转换为int类型的方法
这篇文章将为大家详细讲解有关java把String类型转换为int类型的方法,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
全栈程序员站长
2022/11/10
4.2K0
java把string转int类型_java把String类型转换为int类型的方法
iOS基础【string和Array 互转】&【 string与class互转】& 【json string 和Array互转】
在适配iOS13的时候,经常要对特定类进行特出处理,这个时候class与string之间的互相转换就经常需要使用。
公众号iOS逆向
2021/03/24
1.2K0
iOS基础【string和Array 互转】&【 string与class互转】& 【json string 和Array互转】
Java中将Map转String,String转Map
但很多时候并不能直接将Map对象的toString() 而是应该转换为JsonObject后再调用toString()后存入就正常了
JavaEdge
2021/02/22
14.5K0
jsonobject string转json_java jsonobject转string
这里的JSONObject对像是不是hutool这些工具类的哦,是java内部自带这个。
全栈程序员站长
2022/09/25
3.8K0
String转JsonArray转List[通俗易懂]
场景是查看学生详情时需要展示学生学历信息 比如某某年 哪个学校毕业 奖惩情况等等
全栈程序员站长
2022/08/31
3.2K0
javabyte数组转string_byte数组转string
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/179050.html原文链接:https://javaforall.cn
全栈程序员站长
2022/09/27
3K0
IntPtr 转 string
假设有 intPtr pBuffer 方法一: 直接使用Marshal.PtrToStringAnsi方法: string ss = Marshal.PtrToStringAnsi(pBuffer); 但,如果pBuffer中有\0,此方法所获取的字符串会被截断。这种情况要用方法二。 方法二: 先转为byte数组,然后再转string: byte[] cc = new byte[dwBufSize]; Marshal.Copy(pBuffer, cc, 0, (int)dwBufSi
庞小明
2018/03/09
2.4K0
long转string mybatis_Long转String总结
* 通过测试,发现如果传入null,则第一种方式报错;第二种方式打印出null字符串
全栈程序员站长
2022/08/28
3.3K0
python 数组转换为字典_char转换为string
会触发TypeError: sequence item 0: expected string, int found的错误
全栈程序员站长
2022/11/07
1.1K0
数组转String
这里对文章进行总结:以上就是今天要讲的内容,本文仅仅简单介绍了Java转的数组使用
用户10175992
2022/11/15
3K0
Array,Date,String 对象方法
方法 描述 concat() 连接两个或更多的数组,并返回结果。 copyWithin() 从数组的指定位置拷贝元素到数组的另一个指定位置中。 entries() 返回数组的可迭代对象。 every() 检测数值元素的每个元素是否都符合条件。 fill() 使用一个固定值来填充数组。 filter() 检测数值元素,并返回符合条件所有元素的数组。 find() 返回符合传入测试(函数)条件的数组元素。 findIndex() 返回符合传入测试(函数)条件的数组元素索引。 forEach() 数组每个元素都执行一次回调函数。 from() 通过给定的对象中创建一个数组。 includes() 判断一个数组是否包含一个指定的值。 indexOf() 搜索数组中的元素,并返回它所在的位置。 isArray() 判断对象是否为数组。 join() 把数组的所有元素放入一个字符串。 keys() 返回数组的可迭代对象,包含原始数组的键(key)。 lastIndexOf() 搜索数组中的元素,并返回它最后出现的位置。 map() 通过指定函数处理数组的每个元素,并返回处理后的数组。 pop() 删除数组的最后一个元素并返回删除的元素。 push() 向数组的末尾添加一个或更多元素,并返回新的长度。 reduce() 将数组元素计算为一个值(从左到右)。 reduceRight() 将数组元素计算为一个值(从右到左)。 reverse() 反转数组的元素顺序。 shift() 删除并返回数组的第一个元素。 slice() 选取数组的的一部分,并返回一个新数组。 some() 检测数组元素中是否有元素符合指定条件。 sort() 对数组的元素进行排序。 splice() 从数组中添加或删除元素。 toString() 把数组转换为字符串,并返回结果。 unshift() 向数组的开头添加一个或更多元素,并返回新的长度。 valueOf() 返回数组对象的原始值。
江一铭
2022/07/05
1.2K0
string和array基本方法
  变异方法 :  push() pop() shift() unshift() splice() sort() reverse()  会改变被这些方法调用的原始数组。
刘嘿哈
2022/10/25
4040
alibaba String转json转map
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/145506.html原文链接:https://javaforall.cn
全栈程序员站长
2022/08/27
5K0
String转JSONArray,遍历JSONArray,Array数组转换成JSON字符串
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/151413.html原文链接:https://javaforall.cn
全栈程序员站长
2022/08/31
1.2K0
String转JSONArray,遍历JSONArray,Array数组转换成JSON字符串

相似问题

将Array<String>转换为String,然后返回到Array<String>

26

从Array[((String,String),Double)]转换为Array[(String,Array[((String,String),Double)]]

11

如何将Array[(String,List[String])]转换为Array[(String,String)]

43

配置单元:将array<struct<key:string、value:array<string>>>转换为map<string、array<string>>

10

将array<String^>转换为System::String^

12
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文