如何消除错误 kotlin.UninitializedPropertyAccessException: Lateinit property?

问题描述 投票:0回答:1

我有一个适配器类,并且有一个名为“imageResources”的实例,我已将其声明为 Lateinit,后来我什至确保已给出它。一个值,但我仍然收到此错误。下面是我的 PractiseAdapter.kt

的代码
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.AppCompatButton
import androidx.cardview.widget.CardView
import androidx.recyclerview.widget.RecyclerView
import com.example.visuallithuanian.R
import com.example.visuallithuanian.Utils.shuffleList
import com.example.visuallithuanian.constants.ImageStore


class PractiseAdapter(
    btnShuffle: AppCompatButton,
    recyclerViewPractise: RecyclerView,
) : RecyclerView.Adapter<PractiseAdapter.PractiseViewHolder>() {

    lateinit var recyclerView: RecyclerView
    private var anyCardIsGreen = false
    private var selectedImageResource = -1
    private var selectedImageName = ""
    private var previousSelectedImageResource = -1
    private var previousSelectedImageName = ""
    lateinit var imageResources: MutableList<Int>
    lateinit var imageNames1: MutableList<Pair<String,String>>

    init {
        btnShuffle.setOnClickListener {
            imageResources = mutableListOf()
            imageNames1 =  mutableListOf()

            btnShuffle.setOnClickListener {
                shuffleCards()
            }

        }
    }

    private fun shuffleCards() {

        imageResources = ImageStore.imagesNamesMap.keys.toList().shuffleList().toMutableList()

        imageNames1= imageResources.mapNotNull { it ->
            val pair = ImageStore.imagesNamesMap[it]
            pair?.let { Pair(pair.first, pair.second) }
        }.toList().shuffleList().toMutableList()


        // Reset the selected image and name
        selectedImageResource = -1
        selectedImageName = ""
        previousSelectedImageResource = -1
        previousSelectedImageName = ""

        // Reset the background color of cardImage views to white
        resetCardImageBackgroundToWhite()


        notifyDataSetChanged()
    }

    fun initsetRecyclerView(recyclerView: RecyclerView) {
        this.recyclerView = recyclerView
    }

    private fun resetCardImageBackgroundToWhite() {
        // Iterate through the card views and reset the background color of cardImage to white
        for (position in 0 until imageResources.size) {

            val holder = recyclerView.findViewHolderForAdapterPosition(position) as? PractiseViewHolder
            holder?.cardImagePractise?.setCardBackgroundColor(Color.WHITE)
        }
    }

    companion object {
        val GREEN_COLOR = Color.parseColor("#ABEBC6")
    }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PractiseViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_practise_cards, parent, false)

        return PractiseViewHolder(view)
    }

    override fun getItemCount(): Int = imageResources.size

    override fun onBindViewHolder(holder: PractiseViewHolder, position: Int) {
        val imageResource = imageResources[position]
        val imageName1 = imageNames1[position]


        holder.imageViewPractise.setImageResource(imageResource)
        holder.textViewPractise.text = imageName1.first
        holder.textViewPractise1.text = imageName1.second

        holder.cardImagePractise.setOnClickListener {
            selectedImageResource = imageResource
            previousSelectedImageResource = selectedImageResource
            selectedImageName = ""
            notifyDataSetChanged()
            holder.cardImagePractise.setCardBackgroundColor(GREEN_COLOR)
        }
        holder.cardTextPractise.setOnClickListener {
            if (selectedImageResource == -1) {
                Toast.makeText(
                    it.context,
                    "Please select an image card first.",
                    Toast.LENGTH_SHORT
                ).show()
            } else {
                selectedImageName = imageNames1[position].first
                previousSelectedImageName = selectedImageName
            }
            notifyDataSetChanged()
        }
        val nameColor = if(imageNames1[position].first ==selectedImageName){
            if(ImageStore.imagesNamesMap[selectedImageResource]?.first==selectedImageName){
                Toast.makeText(
                    holder.itemView.context,
                    "Correct name selected!",
                    Toast.LENGTH_SHORT
                ).show()
                anyCardIsGreen=true
                holder.cardTextPractise.setBackgroundColor(GREEN_COLOR) // Set green background for the name card
                Color.GREEN
            } else {
                Toast.makeText(
                    holder.itemView.context,
                    "Wrong name selected!",
                    Toast.LENGTH_SHORT
                ).show()
                Color.RED
            }
        } else {
              holder.cardTextPractise.setBackgroundColor(Color.WHITE)
              Color.WHITE
        }
        holder.cardTextPractise.setBackgroundColor(nameColor)

        // Check if the card is green and set anyCardIsGreen accordingly

    }
    class PractiseViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val cardImagePractise: CardView = itemView.findViewById(R.id.cardImagePractise)
        val cardTextPractise: CardView = itemView.findViewById(R.id.cardTextPractise)
        val imageViewPractise: ImageView = itemView.findViewById(R.id.imageViewPractise)
        val textViewPractise: TextView = itemView.findViewById(R.id.textViewPractise)
        val textViewPractise1: TextView = itemView.findViewById(R.id.textViewPractise1)

    }
}

下面是我的 Singleton 类的代码 ImageStore.kt

import com.example.visuallithuanian.R
import com.example.visuallithuanian.Utils.shuffleList

object ImageStore {

   private val _imagesNamesMap = hashMapOf(
        R.drawable.africa to Pair("Africa","Afrika"),
        R.drawable.asia to Pair("Asia","Azija"),
        R.drawable.europe to Pair("Europe","Europa"),
        R.drawable.antartica to Pair("Antarctica","Antarktida"),
        R.drawable.airplane to Pair("Aeroplane","Lėktuvas"),
        R.drawable.apple1 to Pair("Apple","Obuolys"),
        R.drawable.key to Pair("Key","raktas"),
        R.drawable.sleep to Pair("to sleep","miegoti"),
        R.drawable.shopping to Pair("to shop","apsipirkti"),
        R.drawable.cinemascreen to Pair("to watch a movie","Žiūrėti filmą"),
        R.drawable.goshopping to Pair("I go shopping","aš einu apsipirkti"),
        R.drawable.what1 to Pair("What is it?","Kas tai?"),
        R.drawable.japanesefood to Pair("Japanese food","Japonų maistas"),
        R.drawable.hotcoffee to Pair("hot coffee","karšta kava"),
        R.drawable.eat to Pair("to eat","valgyti"),
        R.drawable.ofcourse to Pair("Of course","Žinoma"),
        R.drawable.rice to Pair("rice","ryžiai"),
        R.drawable.soup1 to Pair("soup","sriuba"),
        R.drawable.bread1 to Pair("Bread","Duona"),
        R.drawable.water1 to Pair("water","vanduo"),
        R.drawable.glass1 to Pair("a glass","stiklinė"),
        R.drawable.apple1 to Pair("apple","obuolys"),
        R.drawable.cost to Pair("to cost","kainuoti"),
        R.drawable.parents1 to Pair("parents","tėvai"),
        R.drawable.classmate to Pair("classmate","klasiokas"),
        R.drawable.friends1 to Pair("my friends","Mano draugai"),
        R.drawable.little to Pair("a little","šiek tiek"),
        R.drawable.go to Pair("Let's go","eikime!"),
        R.drawable.more to Pair("more","daugiau"),
        R.drawable.hand to Pair("hand","ranka"),
        R.drawable.stopsign to Pair("to stop","nustoti"),
        R.drawable.march to Pair("March","Kovas"),
        R.drawable.february to Pair("February","Vasaris"),
        R.drawable.january to Pair("January","Sausis"),
        R.drawable.saturday to Pair("Saturday","Šeštadienis"),
        R.drawable.friday to Pair("Friday","penktadienis"),
        R.drawable.thursday to Pair("Thursday","Ketvirtadienis"),
        R.drawable.wednesday to Pair("Wednesday","Trečiadienis"),
        R.drawable.tuesday to Pair("Tuesday","Antradienis"),
        R.drawable.monday to Pair("Monday","Pirmadienis"),
        R.drawable.sunday to Pair("Sunday","Sekmadienis"),
        R.drawable.autumn to Pair("autumn","ruduo"),
        R.drawable.summer to Pair("Summer","vasara"),
        R.drawable.spring to Pair("Spring","pavasaris"),
        R.drawable.december to Pair("December","Gruodis"),
        R.drawable.november to Pair("November","lapkritis"),
        R.drawable.october to Pair("October","Spalis"),
        R.drawable.september to Pair("September","Rugsėjis"),
        R.drawable.august to Pair("August","Rugpjūtis"),
        R.drawable.july to Pair("July","Liepa"),
        R.drawable.june to Pair("June","Birželis"),
        R.drawable.may to Pair("May","Gegužė"),
        R.drawable.april to Pair("April","Balandis"),
        R.drawable.march to Pair("March","Kovas"),
        R.drawable.noon to Pair("Noon","vidurdienis"),
        R.drawable.morning to Pair("Morning","rytas"),
        R.drawable.evening to Pair("evening","vakaras"),
        R.drawable.beforesleep to Pair("before sleep","prieš miegą"),
        R.drawable.halfaday to Pair("half a day","pusę dienos"),
        R.drawable.midnight to Pair("Midnight","vidurnaktis"),
        R.drawable.decade to Pair("decade","dešimtmetį"),
        R.drawable.season to Pair("Season","sezonas"),
        R.drawable.year to Pair("Year","metai"),
        R.drawable.month to Pair("Month","Mėnuo"),
        R.drawable.day to Pair("day","diena"),
        R.drawable.winter to Pair("winter","žiema"),
        R.drawable.key to Pair("period","laikotarpį"),
        R.drawable.workday to Pair("workday","darbo diena"),
        R.drawable.weekend to Pair("weekend","savaitgalis"),
        R.drawable.twice to Pair("twice","du kartus"),
        R.drawable.once to Pair("once","vieną kartą"),
        R.drawable.week to Pair("week","savaitė"),
        R.drawable.tomorrow to Pair("tomorrow","rytoj"),
        R.drawable.today to Pair("Today","šiandien"),
        R.drawable.inafternoon to Pair("in the afternoon","po pietų"),
        R.drawable.early to Pair("early","anksti"),
        R.drawable.late to Pair("late","vėlai"),

    )
    val imagesNamesMap: Map<Int, Pair<String, String>>
        get() = _imagesNamesMap.toList().shuffled().take(4).toMap()
}

您可以在此图片中查看 Logcat 的内容logcat image

android kotlin android-recyclerview hashmap
1个回答
0
投票
lateinit var imageResources: MutableList<Int>
lateinit var imageNames1: MutableList<Pair<String,String>>

您在

setOnClickListener
中填写这些变量。 这会产生问题。因为需要提前在
init
填写。 (根据您的代码。)

我建议在使用相关变量之前以这种方式检查它们。如果

(::imageResources.isInitialized) {}

此外,直接在 init 中设置值而不用在

setOnClickListener
中会很有好处。

注意

您还可以使用

lazy

© www.soinside.com 2019 - 2024. All rights reserved.