Freya19
Freya19

Reputation: 5

How can I unlock a cardview(replace the layout file) after it qualifies the condition in an adapter class?

I have a Fragment named Flashcards.kt and it's adapter class named FlashcardEasyAdapter. This is the UI image of my fragment screenUI Image so here as you can only first card "Questions and Pronouns" in the Easy cards is unlocked by default and other cards are locked and I have to unlocked as the condition passes. Below is the code of my Flashcards.kt

import android.annotation.SuppressLint
import android.content.Context
import android.content.Context.MODE_PRIVATE
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.navigation.Navigation
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.visuallithuanian.R
import com.example.visuallithuanian.adapter.FlashcardsEasyAdapter
import com.example.visuallithuanian.adapter.FlashcardsHardAdapter
import com.example.visuallithuanian.adapter.FlashcardsMediumAdapter
import com.example.visuallithuanian.custom.FadeEdgeItemDecoration
import com.example.visuallithuanian.data.FlashCardInfo
import com.example.visuallithuanian.ui.activities.FirstScreen
import com.google.android.material.bottomnavigation.BottomNavigationView
import dagger.hilt.android.AndroidEntryPoint


@AndroidEntryPoint
class FlashCards : Fragment() {

lateinit var bottomNav: BottomNavigationView
private lateinit var textCounterFire:TextView
val listItem:MutableList<String> = mutableListOf()

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

    // Inflate the layout for this fragment
    val view = inflater.inflate(R.layout.fragment_flash_cards, container, false)

    // Taking the BottomNavigation view instance from Activity into Fragment
    bottomNav = (activity as? FirstScreen)?.findViewById(R.id.bottomNavigationView)!!
    bottomNav.visibility = View.VISIBLE

    val back_icon = view.findViewById<ImageView>(R.id.back_icon)
    val recyclerViewCardsEasy = view.findViewById<RecyclerView>(R.id.recyclerViewFlashcardsEasy)


    textCounterFire = view.findViewById(R.id.text_counter_fire_flashcard)

    loadTextCountFire()



    recyclerViewCardsEasy.layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)

    val navController = Navigation.findNavController(requireActivity(), R.id.nav_host_fragment)

   

    val easyFlashCardsList = generateEasyFlashCards()
    val adapter1 = FlashcardsEasyAdapter(easyFlashCardsList.toMutableList(), navController,"Questions and Pronouns",textCounterFire)
    recyclerViewCardsEasy.adapter = adapter1


    // Add the custom ItemDecoration for fading effect
    recyclerViewCardsEasy.addItemDecoration(requireContext())
   


    loadSharedPreferences()
    

    // Setting up listener
    back_icon.setOnClickListener {
        activity?.onBackPressed()
    }

    sendData()
    return view
}

private fun sendData() {
    val newCount = textCounterFire.text.toString().toIntOrNull() ?: 0

    val sharedPreferences = requireContext().getSharedPreferences("MyPrefs", MODE_PRIVATE)
    with(sharedPreferences.edit()) {
        putInt("textCount", newCount)
        apply()
    }

    sendUpdateBroadcast(newCount)

}

private fun sendUpdateBroadcast(newCount: Int) {
    val intent = Intent("com.example.UPDATE_TEXT_COUNT")
    intent.putExtra("textCount", newCount)
    requireContext().sendBroadcast(intent)
}

private fun loadTextCountFire() {
    val sharedPreferences: SharedPreferences = requireActivity().getSharedPreferences("MyPrefs", MODE_PRIVATE)
    val savedCount = sharedPreferences.getInt("textCount", 0)
    textCounterFire.text = savedCount.toString()
}

private fun loadSharedPreferences() {
    val sharedPreferences = requireContext().getSharedPreferences("MyPrefs", Context.MODE_PRIVATE)
    val counter = sharedPreferences.getInt("counter", 0)
    val counterDiamond = sharedPreferences.getInt("counterDiamond", 0)
    val counterGem = sharedPreferences.getInt("counterGem", 0)

    // Update UI with retrieved values
    view?.findViewById<TextView>(R.id.text_counter_fire_flashcard)?.text = counter.toString()
    view?.findViewById<TextView>(R.id.text_counter_diamond_flashcard)?.text = counterDiamond.toString()
    view?.findViewById<TextView>(R.id.text_counter_gem_flashcard)?.text = counterGem.toString()
}


private fun generateEasyFlashCards(): List<FlashCardInfo> {
    return listOf(
        FlashCardInfo(R.drawable.doctorvisit, "Questions and Pronouns", "",0,R.drawable.fireicon),
        FlashCardInfo(R.drawable.pointers, "Pointers", "",5,R.drawable.fireicon),
        FlashCardInfo(R.drawable.talking, "Daily Basic", "",30,R.drawable.fireicon),
        FlashCardInfo(R.drawable.action, "Basic actions", "",40,R.drawable.fireicon),
        FlashCardInfo(R.drawable.holiday1, "Holidays, Celebration", "",50,R.drawable.fireicon),
        FlashCardInfo(R.drawable.relatives, "Family", "",65,R.drawable.fireicon),
        FlashCardInfo(R.drawable.keyphrase, "Key Phrases", "",70,R.drawable.fireicon),
        FlashCardInfo(R.drawable.days, "Day and Months", "",75,R.drawable.fireicon),
        FlashCardInfo(R.drawable.colorshape, "Colours and Shapes", "",80,R.drawable.fireicon),
        FlashCardInfo(R.drawable.iverb, "I verbs", "",85,R.drawable.fireicon),
        FlashCardInfo(R.drawable.workplace, "Workplace language", "",90,R.drawable.fireicon),
        FlashCardInfo(R.drawable.nature, "Nature", "",95,R.drawable.fireicon),
        FlashCardInfo(R.drawable.romantic, "Romantic phrases", "",100,R.drawable.fireicon)
    )
}


}

below is the code of the adapter class

import android.content.Context
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.app.AlertDialog
import androidx.cardview.widget.CardView
import androidx.navigation.NavController
import androidx.recyclerview.widget.RecyclerView
import com.example.visuallithuanian.R
import com.example.visuallithuanian.data.FlashCardInfo

class FlashcardsEasyAdapter(
private val imageList: MutableList<FlashCardInfo>,  // Mutable list to allow updates
private val navController: NavController,
private val unlockedItem: String = "Questions and Pronouns",
private val textCounterFire: TextView,
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

companion object {
    private const val VIEW_TYPE_UNLOCKED = 0
    private const val VIEW_TYPE_LOCKED = 1
}

inner class UnlockedViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    val imageViewFlashcards: ImageView = itemView.findViewById(R.id.imageViewFlashcards)
    val textViewFlashcards: TextView = itemView.findViewById(R.id.textflashCardName)
    val cardviewFlashcard: CardView = itemView.findViewById(R.id.cardFlashCards)
}


inner class LockedViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    val cardviewFlashcardFire: CardView = itemView.findViewById(R.id.cardFlashCardsFire)
    val textLock: TextView = itemView.findViewById(R.id.textflashCardName)
    val imageLock: ImageView = itemView.findViewById(R.id.imageViewLock)
    val fireCountTextView: TextView = itemView.findViewById(R.id.topRightTextView)
}

override fun getItemViewType(position: Int): Int {
    return if (imageList[position].name == unlockedItem) VIEW_TYPE_UNLOCKED else VIEW_TYPE_LOCKED
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
    val view: View = if (viewType == VIEW_TYPE_LOCKED) {
        LayoutInflater.from(parent.context).inflate(R.layout.items_flashcard_lockedfire, parent, false)
    } else {
        LayoutInflater.from(parent.context).inflate(R.layout.item_flashcards, parent, false)
    }
    return if (viewType == VIEW_TYPE_LOCKED) LockedViewHolder(view) else UnlockedViewHolder(view)
}

override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
    val flashCard = imageList[position]
    if (holder is UnlockedViewHolder) {
        holder.imageViewFlashcards.setImageResource(flashCard.imageId)
        holder.textViewFlashcards.text = flashCard.name
        holder.cardviewFlashcard.setOnClickListener {
            when (flashCard.name) {
                "Questions and Pronouns" -> navController.navigate(R.id.action_flashCards_to_questionsFragment)
                "Pointers" -> navController.navigate(R.id.action_flashCards_to_pointersFlashcardFragment)
                "Daily Basic" -> navController.navigate(R.id.action_flashCards_to_dailyBasic)
                "Day and Months" -> navController.navigate(R.id.action_flashCards_to_daysMonthsFlashcards)
                "Key Phrases" -> navController.navigate(R.id.action_flashCards_to_keyPhrasesFragment)
                "Basic actions" -> navController.navigate(R.id.action_flashCards_to_basicActionsFlashcard)
                "Family" -> navController.navigate(R.id.action_flashCards_to_familyFlashcards)
                "Workplace language" -> navController.navigate(R.id.action_flashCards_to_workPlaceLanguage)
                "I verbs" -> navController.navigate(R.id.action_flashCards_to_verbsFragment)
                "Holidays, Celebration" -> navController.navigate(R.id.action_flashCards_to_holidayCelebrations)
                "Nature" -> navController.navigate(R.id.action_flashCards_to_natureFragment)
                "Colours and Shapes" -> navController.navigate(R.id.action_flashCards_to_colorshapeFragment)
                "Romantic phrases" -> navController.navigate(R.id.action_flashCards_to_romanticPhrasesFragment)
            }
        }
    } else if (holder is LockedViewHolder) {
        holder.textLock.text = flashCard.name
        holder.imageLock.setImageResource(R.drawable.lockpic)
        holder.fireCountTextView.text = flashCard.topRightValue.toString()

        holder.cardviewFlashcardFire.setOnClickListener {
            if (flashCard.name != "Questions and Pronouns") {
                val dialogView = LayoutInflater.from(holder.itemView.context)
                    .inflate(R.layout.dialog_custom_message, null)

                val messageTextView: TextView = dialogView.findViewById(R.id.dialogMessage)
                val imageView: ImageView = dialogView.findViewById(R.id.dialogImage)

                messageTextView.text = "Do you have ${flashCard.topRightValue}"
                imageView.setImageResource(R.drawable.fireicon)

                AlertDialog.Builder(holder.itemView.context)
                    .setTitle("Category Locked")
                    .setView(dialogView)
                    .setNegativeButton("NO") { dialog, _ -> dialog.cancel() }
                    .setPositiveButton("YES") { _, _ ->
                        try {
                            val currentCount = textCounterFire.text.toString().toInt()
                            val fireCount = flashCard.topRightValue
                            if (currentCount >= fireCount) {
                                val newCount = currentCount - fireCount
                                textCounterFire.text = newCount.toString()

                                // Save the new value to SharedPreferences
                                val sharedPreferences = holder.itemView.context.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE)
                                val editor = sharedPreferences.edit()
                                editor.putInt("textCount", newCount)
                                editor.apply()

                                //How can i replace locked layout folder with unlocked layout folder when the condition matches
                                // for specific cardview
                                if (flashCard.topRightValue ==5){
                                    imageList[position] == flashCard.copy(name = "Pointers")   // This line of code is not working
                                    Toast.makeText(
                                        holder.itemView.context,
                                        "Card Unlocked",
                                        Toast.LENGTH_SHORT
                                    ).show()
                                }

                            } else {
                                Toast.makeText(holder.itemView.context, "Not enough points", Toast.LENGTH_SHORT).show()
                            }
                        } catch (e: NumberFormatException) {
                            e.printStackTrace()
                        }
                    }
                    .show()
            }
        }
    }
}

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

}

Below is the code of the data class FlashCardInfo

data class FlashCardInfo(val imageId:Int,
                     var name:String,
                     val translation:String,
                     val topRightValue:Int,
                     val topRightImage:Int)

So my condition does get passed in the adapter class and the the Toast message of "Card Unlocked" also gets displayed but my Cardview doesn't get displayed, it's locked layout doesn't changed to unlocked layout an i am not able to able access the "Pointers" flashcard here.

I tried to manually the position of the string by connecting it with imagelist position but still layout of the cardview is not unlocking (For example "Pointers") in this case. I want card "Pointers" to get unlocked so i can access the content inside it

Upvotes: 0

Views: 17

Answers (0)

Related Questions