So, I am trying to pass the data of all the saved cardviews into and show them in another fragment (ToLearnFragment.kt) so when I click on the star icon the data gets stored. so I am using room database for it, i have created the Room database and also created the repository and the viewmodel required and finally when i try to pass the data through bundle using putParcelableArrayList I am getting an error in it's value.
FlashCardData.kt
@Entity(tableName = "flashcards")
data class FlashcardData(
val front:String,
val back:String,
)
FlashcardsDao.kt
@Dao
interface FlashCardsDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertFlashcard(flashcard: FlashcardData)
@Query("SELECT * FROM flashcards")
fun getAllFlashcards(): LiveData<List<FlashcardData>>
}
Below is the Room Database class FlashcardRoomDatabase.kt
@Database(entities = [FlashCards::class], version = 1, exportSchema = false)
abstract class FlashCardRoomDatabase:RoomDatabase() {
abstract fun flashCardsDao():FlashCardsDao
companion object{
@Volatile
private var instance:FlashCardRoomDatabase?=null
fun getDatabase(context:Context):FlashCardRoomDatabase{
val tempInstance = instance
if(tempInstance!=null){
return tempInstance
}
synchronized(this){
val INSTANCE = Room.databaseBuilder(
context.applicationContext,
FlashCardRoomDatabase::class.java,
"flashcard_database"
).build()
instance=INSTANCE
return INSTANCE
}
}
}
}
The repository class WordRepository.kt
class WordRepository(@Inject private val flashCardsDao: FlashCardsDao) {
val allwords: LiveData<List<FlashcardData>> = flashCardsDao.getAllFlashcards()
suspend fun insertFlashCard(flashCards:FlashcardData){
flashCardsDao.insertFlashcard(flashCards)
}
suspend fun getAllWords(){
flashCardsDao.getAllFlashcards()
}
}
below is my ViewModel class FlashcardviewModel.kt
class FlashcardViewModel(application: Application,@Inject private var repository: WordRepository):AndroidViewModel(application) {
init {
val flashCardsDao = FlashCardRoomDatabase.getDatabase(application).flashCardsDao()
repository = WordRepository(flashCardsDao)
}
val allFlashcards: LiveData<List<FlashcardData>> = repository.allwords
fun insertFlashCard(flashCards: FlashcardData) = viewModelScope.launch {
repository.insertFlashCard(flashCards)
}
fun getAllWords() = viewModelScope.launch {
repository.getAllWords()
}
}
My Fragment class QuestionsFragment.kt
@AndroidEntryPoint
class QuestionsFragment : Fragment() {
lateinit var binding: FragmentQuestionsBinding
lateinit var viewModel: BottomNavigationViewModel
lateinit var counterviewModel:ToLearnViewModel
lateinit var bottomNavigationView: BottomNavigationView
lateinit var flashcardviewModel: FlashcardViewModel
private val hashMap = HashMap<String,String>()
private var currentPairIndex =0
private lateinit var currentPair:Map.Entry<String,String>
var isFront=true
private val totalPairs = 17 // change the value to the actual number of entries in your hashMap
@SuppressLint("ResourceType")
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
binding = FragmentQuestionsBinding.inflate(inflater, container, false)
bottomNavigationView = (activity as? FirstScreen)?.findViewById(R.id.bottomNavigationView)!!
viewModel = ViewModelProvider(requireActivity())[BottomNavigationViewModel::class.java]
counterviewModel = ViewModelProvider(requireActivity())[ToLearnViewModel::class.java]
flashcardviewModel = ViewModelProvider(requireActivity())[FlashcardViewModel::class.java]
bottomNavigationView.visibility = View.GONE
binding.textCounter.text = counterviewModel.count.toString()
// setting up listener for back Icon
binding.backIcon?.setOnClickListener {
activity?.onBackPressed()
}
binding.floatingActionButton.setOnClickListener {
findNavController().navigate(R.id.action_questionsFragment_to_flashCards)
}
//changing color of progress bar progress
binding.progressHorizontal.progressTintList = ColorStateList.valueOf(ContextCompat.getColor(requireContext()
,R.color.blue_card))
//changing color of background color of progress bar
binding.progressHorizontal.progressBackgroundTintList = ColorStateList.valueOf(ContextCompat.getColor(requireContext(),
R.color.silver))
// Hashmap of strings that will shown on cardview front and back side
hashMap["What"] = "Kas"
hashMap["When"] = "Kai"
hashMap["Where"] = "Kur"
hashMap["Who"] = "Kas"
hashMap["Whom"] = "Kam"
hashMap["Why"] = "Kodėl"
hashMap["How"] = "Kaip"
hashMap["Which"] = "Kuris/kuri"
hashMap["Whose"] = "Kieno"
hashMap["I"] = "aš"
hashMap["you (singular)"] = "tu/jūs (informal/formal)"
hashMap["he"] = "jis"
hashMap["she"] = "ji"
hashMap["it "] = "tai"
hashMap["we"] = "mes"
hashMap["you (plural)"] = "jūs"
hashMap["they"] = "jie"
val front_animation = AnimatorInflater.loadAnimator(context, R.anim.front_animator) as AnimatorSet
val back_animation = AnimatorInflater.loadAnimator(context,R.anim.back_animator)as AnimatorSet
// retrieve the current pair from the hashMap
currentPair = hashMap.entries.elementAt(currentPairIndex)
binding.textCardFront.text = currentPair.key
binding.textCardBack.text = hashMap[currentPair.key]
// onclick listener on the image
binding.imageFlashCard.setOnClickListener {
counterviewModel.addWordCount()
binding.textCounter.text = counterviewModel.count.toString()
// increment currentPairIndex and get the next pair
currentPairIndex++
if (currentPairIndex >= hashMap.size) {
// if we have reached the end of the hashmap, start again from the beginning
currentPairIndex = 0
}
currentPair = hashMap.entries.elementAt(currentPairIndex)
// update the UI with the new pair
binding.textCardFront.text = currentPair.key
binding.textCardBack.text = hashMap[currentPair.key]
//store data in the room database
val flashCards = FlashcardData(front = currentPair.key, back = hashMap[currentPair.key]!!)
flashcardviewModel.insertFlashCard(flashCards)
// retrieve all the data from the Room Database and pass it to the LearnFragment
val allFlashCards = flashcardviewModel.getAllWords()
val bundle = Bundle()
bundle.putParcelableArrayList("flashcards",ArrayList(allFlashCards)) // I am getting error here at ArrayList(allFlashCards)
val learnFragment = ToLearnFragment()
learnFragment.arguments = bundle
}
//Onclick listener for the counterButton
binding.cardLearning.setOnClickListener {
// navigate to the LearnFragment
findNavController().navigate(R.id.action_questionsFragment_to_toLearnFragment)
}
//onclick listener for the Flip button
with(binding) {
btnFlip.setOnClickListener {
val progress = ((currentPairIndex + 1) * 100) / totalPairs
binding.progressHorizontal.progress = progress
// initialize currentPairIndex to 0 if it hasn't been initialized yet
if (currentPairIndex < 0) {
currentPairIndex = 0
}
if (isFront) {
front_animation.setTarget(textCardFront)
back_animation.setTarget(textCardBack)
front_animation.start()
back_animation.start()
isFront = false
textCardBack.visibility = View.VISIBLE
textCardFront.visibility = View.GONE
imageFlashCard.visibility = View.GONE
cardViewQuestions.setCardBackgroundColor(ContextCompat.getColor(requireContext(), R.color.pink))
} else {
currentPairIndex = (currentPairIndex + 1) % hashMap.size
textCardFront.visibility = View.VISIBLE
textCardBack.visibility = View.GONE
imageFlashCard.visibility = View.VISIBLE
cardViewQuestions.setCardBackgroundColor(ContextCompat.getColor(requireContext(), R.color.blue_card))
front_animation.setTarget(textCardBack)
back_animation.setTarget(textCardFront)
back_animation.start()
front_animation.start()
isFront = true
}
// retrieve the current pair from the hashMap
currentPair = hashMap.entries.elementAt(currentPairIndex)
binding.textCardFront.text = currentPair.key
binding.textCardBack.text = hashMap[currentPair.key]
}
}
return binding.root
}
}