App closes after intent activity change - Kotlin - android

I have an image gallery on a Fragment and I want to create a program that, once the user clicks on a certain image, the program redirects the user to an Activity where more details are presented. However, after implementing the Intent, the program just crashes when the Activity opens.
I don't know what I might be doing wrong as I do not have much experience with fragments (I believe it is something I'm doing wrong in the fragment intent)
Here's the code:
Fragment
package cm.a12872_a18797.favlist.fragments
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.fragment.app.Fragment
import cm.a12872_a18797.favlist.ImageDetailActivity
import cm.a12872_a18797.favlist.Modal
import cm.a12872_a18797.favlist.R
class HomeFragment : Fragment() {
lateinit var rootView: View
public val modalList = ArrayList<Modal>()
lateinit var gridView: GridView
private var descriptions = arrayOf(
"Golden Bridge", "Tampa Bay Buccaneers", "Chevrolet Camaro",
"Vegetable Casserole", "Sweet and Sour Chicken", "Design Vector",
"Pork Loin", "Sidney's Opera House", "Pasta Dish",
"Dope Setup", "Singapore", "Tacos Dish",
"Toquio", "Warm Salad Dish"
)
private var images = intArrayOf(
R.drawable.bridge, R.drawable.buccaneers, R.drawable.camaro,
R.drawable.casserole, R.drawable.chicken, R.drawable.design,
R.drawable.lombo, R.drawable.operahouse, R.drawable.pasta,
R.drawable.setup, R.drawable.singapore, R.drawable.tacos,
R.drawable.toquio, R.drawable.warmsalad
)
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
rootView = inflater.inflate(R.layout.fragment_home, container, false)
gridView = rootView.findViewById(R.id.home_grid)
for (i in descriptions.indices){
modalList.add(Modal(descriptions[i], images[i]))
}
var customAdapter = GridAdapter(modalList, this#HomeFragment.requireContext())
gridView.adapter = customAdapter
gridView.setOnItemClickListener() { adapterView, view, position, l ->
var intent = Intent(this#HomeFragment.requireContext(), ImageDetailActivity::class.java)
intent.putExtra("data", modalList[position])
startActivity(intent)
}
return rootView
}
class GridAdapter(var itemModel : ArrayList<Modal>, var context: Context): BaseAdapter(){
var layoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
var view = convertView
if (view == null){
view = layoutInflater.inflate(R.layout.home_grid_row, parent, false)
}
var imageViewName = view?.findViewById<ImageView>(R.id.grid_image)
imageViewName?.setImageResource(itemModel[position].image!!)
return view!!
}
override fun getItem(position: Int): Any {
return itemModel[position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getCount(): Int {
return itemModel.size
}
}
}
Activity:
package cm.a12872_a18797.favlist
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import cm.a12872_a18797.favlist.fragments.HomeFragment
import cm.a12872_a18797.favlist.fragments.ListsFragment
import cm.a12872_a18797.favlist.fragments.SearchFragment
import com.google.android.material.bottomnavigation.BottomNavigationView
class ImageDetailActivity : AppCompatActivity() {
val TAG = "ImageDetailActivity"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_image_detail)
//region Bottom Navigation Menu =====================================
val bottomNavigation: BottomNavigationView = findViewById(R.id.bottom_navigation)
val homeFragment = HomeFragment()
val listsFragment = ListsFragment()
val searchFragment = SearchFragment()
bottomNavigation.setOnNavigationItemSelectedListener {
when (it.itemId) {
R.id.nav_home -> {
setCurrentFragment(homeFragment)
Log.i(TAG, "Home Selected")
}
R.id.nav_lists -> {
setCurrentFragment(listsFragment)
Log.i(TAG, "My Lists Selected")
}
R.id.nav_search -> {
setCurrentFragment(searchFragment)
Log.i(TAG, "Search Selected")
}
}
true
}
//endregion ==
val detailText = findViewById<TextView>(R.id.detailText)
val detailImage = findViewById<ImageView>(R.id.detailImage)
var modalItems: Modal = intent.getSerializableExtra("data") as Modal
detailText.text = modalItems.name
detailImage.setImageResource(modalItems.image!!)
}
private fun setCurrentFragment(fragment : Fragment) =
supportFragmentManager.beginTransaction().apply {
replace(R.id.fl_wrapper, fragment)
commit()
}
}
Modal Class:
package cm.a12872_a18797.favlist
import java.io.Serializable
class Modal : Serializable {
var name:String? = null
var image:Int? = null
constructor(name:String, image:Int){
this.name = name
this.image = image
}
}

Related

How to call a method in adapter from a fragment in kotlin?

I have been trying to call a function from fragment to adapter, but I can't approach it right.
I want to invisible the button present in the fragment from adapter.
**My Adapter Code:**
package com.littleboo.brandlogo.Adapters
import android.R
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.os.Build
import android.os.VibrationEffect
import android.os.Vibrator
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat.getSystemService
import androidx.recyclerview.widget.RecyclerView
import com.littleboo.brandlogo.Fragments.QuizFragment
import com.littleboo.brandlogo.MainActivity
import com.littleboo.brandlogo.Models.Question
import com.littleboo.brandlogo.databinding.ActivityMainBinding.inflate
import com.littleboo.brandlogo.databinding.FragmentQuizBinding
import kotlinx.coroutines.NonDisposableHandle.parent
class QuestionAdap(val context: Context, val question: Question) :
RecyclerView.Adapter<QuestionAdap.OptionViewHolder>() {
var index = 1
var score = 0
val animShake: Animation = AnimationUtils.loadAnimation(context, com.littleboo.brandlogo.R.anim.shake)
private var options: List<String> = listOf(question.option1, question.option2, question.option3, question.option4)
inner class OptionViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
var optionView = itemView.findViewById<TextView>(com.littleboo.brandlogo.R.id.quiz_option)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OptionViewHolder {
val view = LayoutInflater.from(context).inflate(com.littleboo.brandlogo.R.layout.quizoptions, parent, false)
return OptionViewHolder(view)
}
override fun onBindViewHolder(holder: OptionViewHolder, position: Int) {
holder.optionView.text = options[position]
holder.itemView.setOnClickListener {
question.userAnswer = options[position]
notifyDataSetChanged()
}
if(question.userAnswer == options[position] && question.userAnswer == question.answer){
holder.itemView.setBackgroundResource(com.littleboo.brandlogo.R.drawable.option_item_selected_bg)
score += 10
Toast.makeText(context,"Score is $score", Toast.LENGTH_SHORT).show()
}
else if(question.userAnswer == options[position] && question.userAnswer != question.answer){
holder.itemView.setBackgroundResource(com.littleboo.brandlogo.R.drawable.wrong_option_item_selected_bg)
holder.itemView.startAnimation(animShake)
}
else{
holder.itemView.setBackgroundResource(com.littleboo.brandlogo.R.drawable.non_option_item_selected_bg)
}
}
override fun getItemCount(): Int {
return options.size
}
}
My Quiz Fragment Code:
package com.littleboo.brandlogo.Fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.CircularProgressDrawable
import com.bumptech.glide.Glide
import com.google.firebase.firestore.FirebaseFirestore
import com.littleboo.brandlogo.Adapters.QuestionAdap
import com.littleboo.brandlogo.Models.Question
import com.littleboo.brandlogo.Models.quizmodel
import com.littleboo.brandlogo.R
import com.littleboo.brandlogo.databinding.FragmentQuizBinding
class QuizFragment : Fragment(){
lateinit var binding: FragmentQuizBinding
var quizzes: MutableList<quizmodel>? = null
private var questions = mutableMapOf<String, Question>()
private lateinit var mArraylist: ArrayList<Question>
var index = 1
private lateinit var mfirestore: FirebaseFirestore
private lateinit var mrecycler: RecyclerView
lateinit var myadapter: QuestionAdap
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentQuizBinding.inflate(layoutInflater)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mrecycler = binding.optionList
mrecycler.layoutManager
myadapter = QuestionAdap(requireContext(),Question())
mArraylist = arrayListOf()
questions.map { it.key to it.value }.shuffled().toMap()
setUpFirestore()
setUpEventListener()
}
override fun onDestroy() {
super.onDestroy()
mfirestore.terminate()
// finish()
}
private fun setUpEventListener() {
binding.nextbtn.setOnClickListener {
index++
bindViews()
}
// binding.btnSubmit.setOnClickListener {
// Log.d("FINALQUIZ", questions.toString())
// val intent = Intent(this, ResultActivity::class.java)
// val json = Gson().toJson(quizzes!![0])
// intent.putExtra("QUIZ", json)
// startActivity(intent)
// finish()
// }
}
private fun setUpFirestore() {
mfirestore = FirebaseFirestore.getInstance()
val quizTitle = activity?.intent?.getStringExtra("title")
if (quizTitle != null) {
mfirestore.collection("Quizes").whereEqualTo("title", quizTitle)
.get()
.addOnSuccessListener {
if (it != null && !it.isEmpty) {
quizzes = it.toObjects(quizmodel::class.java)
questions = quizzes!![0].questions
shuffle()
bindViews()
}
}
}
}
private fun bindViews() {
// btnPrevious.visibility = View.GONE
// binding.btnSubmit.visibility = View.GONE
// binding.btnNext.visibility = View.GONE
// if (index == 1) { //first question
// binding.btnNext.visibility = View.VISIBLE
// } else if (index == questions!!.size) { // last question
// binding.btnSubmit.visibility = View.VISIBLE
//// btnPrevious.visibility = View.VISIBLE
// } else { // Middle
//// btnPrevious.visibility = View.VISIBLE
// binding.btnNext.visibility = View.VISIBLE
// }
val circularProgressDrawable = CircularProgressDrawable(requireContext())
circularProgressDrawable.strokeWidth = 8f
// circularProgressDrawable.colorFilter = ("#ac5fe1")
circularProgressDrawable.centerRadius = 30f
circularProgressDrawable.start()
val question = questions!!["question$index"]
question?.let {
Glide.with(this).load(it.imagequiz).placeholder(circularProgressDrawable).into(binding.imagequiz)
val optionAdapter = QuestionAdap(requireContext(), it)
mrecycler.layoutManager = LinearLayoutManager(requireContext())
mrecycler.adapter = optionAdapter
mrecycler.setHasFixedSize(true)
}
}
private fun shuffle() {
val keys = questions.keys.toMutableList().shuffled()
val values = questions.values.toMutableList().shuffled()
keys.forEachIndexed { index, key ->
questions[key] = values[index]
}
}
}
I tried calling fragment in adapter like:
QuizFragment().binding.btnxt.visibility = View.Visible
in BindViewHolder function.
Thank You
You can use kotlin lambda function to achieve it. Like this
class QuestionAdap(val context: Context, val question: Question, var onItemClicked: ((boolean) -> Unit))
call onItemClicked in your adapter where you want it
and in fragment
myadapter = QuestionAdap(requireContext(),Question()) { boolean ->
if (boolean) {
//hide/show
} else {
//hide/show
}
}
You can use the Callback functions of kotlin in your fragment, which will be passed into your adapter. So whenever you invoke that callback from your adapter, it will be triggered in your fragment.
Step 1: Create a method like the one below in your fragment.
private fun showHideButtonFromAdapter (
isButtonVisible: Boolean
) {
// set your button visibility according to isButtonVisible value.
}
Step 2: pass a method from your fragment to adapter as argument
val adapter = YourAdapter(::showHideButtonFromAdapter)
// set above adapter in your recycler view.
Step 3: In your adapter invoke that callback function like the one below.
class ColorPickerAdapter constructor(
private val onItemClicked: (Boolean) -> Unit
) : RecyclerView.Adapter<YourAdapter.ViewHolder>() {
// your other adapter methods here
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
onItemClicked.invoke(pass true or false as per your requirement)
// above invocation will trigger an event in the fragment.
}
}
In your adapter there need to be instance of your fragment, so change it like:
class QuestionAdap(val context: Context, val question: Question, fragment: Fragment) :
RecyclerView.Adapter<QuestionAdap.OptionViewHolder>() {
Then you can call your fragment by simply writing fragment in your adapter like:
override fun onBindViewHolder(holder: OptionViewHolder, position: Int) {
holder.optionView.text = options[position]
holder.itemView.setOnClickListener {
question.userAnswer = options[position]
notifyDataSetChanged()
}
//Example
fragment.shuffle()
And you need to send this fragment instance when you create it's adapter, so in your fragment use this:
myadapter = QuestionAdap(requireContext(),Question(), this)

Getting first index of each list in a nested list in Kotlin

I'm retrieving a list of lists from an API in JSON. This is how the response looks like.
{
"result":"success",
"documentation":"https://www.exchangerate-api.com/docs",
"terms_of_use":"https://www.exchangerate-api.com/terms"
"supported_codes":[
["AED","UAE Dirham"],
["AFN","Afghan Afghani"],
["ALL","Albanian Lek"],
["AMD","Armenian Dram"],
["ANG","Netherlands Antillian Guilder"],
["AOA","Angolan Kwanza"],
["ARS","Argentine Peso"],
["AUD","Australian Dollar"],
["AWG","Aruban Florin"],
["AZN","Azerbaijani Manat"],
["BAM","Bosnia and Herzegovina Convertible Mark"],
["BBD","Barbados Dollar"] etc. etc.
]
}
And this is the data class
data class CurrencyResponse(
#Json(name="documentation") val documentation: String,
#Json(name="result") val result: String,
#Json(name="supported_codes") val supported_codes: List<List<String>>,
#Json(name="terms_of_use") val terms_of_use: String
)
I managed to get the list of lists(supported_codes) but what I want now is to get the first index of each list(AED,AFN,ALL,etc.) and store them in a list, convert it to an array, then use that array to populate my spinners. Can anyone help me out with that?
Below is the relevant code.
Thank you.
CurrencyRepository.kt
package com.example.currencyconverter.data
import com.example.currencyconverter.BuildConfig
import javax.inject.Inject
import javax.inject.Singleton
#Singleton
class CurrencyRepository #Inject constructor(private val currencyApi: CurrencyApi) {
suspend fun getConversionRate(baseCurrency: String, toCurrency: String, amount: Double?): ConversionResponse {
return currencyApi.convert(BuildConfig.API_KEY, baseCurrency, toCurrency, amount)
}
suspend fun getCurrencies(): List<String> {
return currencyApi.getCurrencies(BuildConfig.API_KEY).supported_codes
}
}
CurrencyViewModel.kt
package com.example.currencyconverter.ui
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.currencyconverter.data.CurrencyRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject
#HiltViewModel
class CurrencyViewModel #Inject constructor(private val repository: CurrencyRepository): ViewModel() {
private val _conversionResult = MutableLiveData<String>()
val conversionResult: LiveData<String> = _conversionResult
private val _currencies = MutableLiveData<List<String>>()
val currencies: LiveData<List<String>> = _currencies
init {
getCurrencies()
}
fun getConversionRate(baseCurrency: String, toCurrency: String, amount: Double?) {
viewModelScope.launch {
_conversionResult.value = repository.getConversionRate(baseCurrency, toCurrency, amount).conversion_result
}
}
fun getCurrencies() {
viewModelScope.launch {
_currencies.value = repository.getCurrencies()
}
}
}
HomeFragment.kt
package com.example.currencyconverter.ui
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.example.currencyconverter.R
import com.example.currencyconverter.databinding.FragmentHomeBinding
import dagger.hilt.android.AndroidEntryPoint
#AndroidEntryPoint
class HomeFragment : Fragment(R.layout.fragment_home) {
private val viewModel by viewModels<CurrencyViewModel>()
private var _binding: FragmentHomeBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
_binding = FragmentHomeBinding.bind(view)
lateinit var firstCurrency: String
lateinit var secondCurrency: String
viewModel.currencies.observe(viewLifecycleOwner) {
binding.list.text = " ${it[0]} , ${it[1]} "
}
var currenciesFormat = arrayOf(viewModel.currencies.value?.get(0),
viewModel.currencies.value?.get(1)
)
binding.apply {
spinnerFirst.adapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, currenciesFormat)
spinnerFirst.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
adapterView: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
firstCurrency = adapterView?.getItemAtPosition(position).toString()
}
override fun onNothingSelected(p0: AdapterView<*>?) {
}
}
spinnerSecond.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
adapterView: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
secondCurrency = adapterView?.getItemAtPosition(position).toString()
}
override fun onNothingSelected(p0: AdapterView<*>?) {
}
}
}
binding.constraintLayout.setOnTouchListener(object : View.OnTouchListener {
override fun onTouch(p0: View?, p1: MotionEvent?): Boolean {
closeKeyboard(p0)
return true
}
})
binding.button.setOnClickListener {
val stringInTextField = binding.amountText.text.toString()
val amount = stringInTextField.toDoubleOrNull()
if (amount == null) {
binding.resultText.text = " "
}
closeKeyboard(binding.amountText)
viewModel.getConversionRate(firstCurrency, secondCurrency, amount)
viewModel.conversionResult.observe(viewLifecycleOwner) {
binding.resultText.text = it
}
}
}
private fun closeKeyboard(view: View?) {
val imm =
view?.context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
if (view != null) {
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
}
}
You can use kotlin.collections's map function. https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/map.html
fun main(){
val supportedCodes = listOf(
listOf("AED","UAE Dirham"),
listOf("AFN","Afghan Afghani"),
listOf("ALL","Albanian Lek")
)
val codes = supportedCodes.map { it[0] }
println(codes)
}
The output is a list containing just the first element from each nested list.
[AED, AFN, ALL]

One checkbox triggering another checkbox in a different layout

I'm currently writing an app that displays a list of movies. I have many fragments that display a cardview containing movies, and each cardview has a checkbox. The user can press on the cardview to go to the details page of the movie where another checkbox is present.
The goal of both checkboxes is to add the movie to the favorites tab.
My question is, how can I make the checkbox that is inside the details page checked when the user checks the one in the cardview?
Below is the relevant code.
Appreciate all the help I can get.
MoviesListFragment.kt
package com.example.moviesapp.ui.Fragments
import android.os.Bundle
import android.view.*
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.moviesapp.R
import com.example.moviesapp.databinding.FragmentMoviesListBinding
import com.example.moviesapp.network.MoviesFavorites
import com.example.moviesapp.network.MoviesResults
import com.example.moviesapp.ui.DaoViewModel
import com.example.moviesapp.ui.MovieApiStatus
import com.example.moviesapp.ui.MoviesListAdapter
import com.example.moviesapp.ui.MoviesListViewModel
import dagger.hilt.android.AndroidEntryPoint
#AndroidEntryPoint
class MoviesListFragment : Fragment(R.layout.fragment_movies_list), MoviesListAdapter.OnItemClickListener {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_movies_list, container, false)
}
private val daoViewModel by viewModels<DaoViewModel>()
private val viewModel by viewModels<MoviesListViewModel>()
private var _binding: FragmentMoviesListBinding? = null
private val binding get() = _binding!!
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//View is inflated layout
_binding = FragmentMoviesListBinding.bind(view)
val adapter = MoviesListAdapter(this)
binding.apply {
recyclerView.layoutManager = LinearLayoutManager(requireContext())
//Disable animations
recyclerView.setHasFixedSize(true)
recyclerView.adapter = adapter
}
//Observe the movies livedata
//Use viewLifecycleOwner instead of this because the UI should stop being updated when the fragment view is destroyed
viewModel.getTrending()
viewModel.moviesTrending.observe(viewLifecycleOwner) {
adapter.submitList(it)
}
viewModel.networkState.observe(viewLifecycleOwner, {
binding.progressBar.isVisible = if (it==MovieApiStatus.LOADING) true else view.isGone
binding.buttonRetry.isVisible = if(it==MovieApiStatus.ERROR) true else view.isGone
binding.errorTextView.isVisible = if(it==MovieApiStatus.ERROR) true else view.isGone
binding.recyclerView.isVisible = if(it==MovieApiStatus.DONE) true else view.isGone
binding.noResultsText.isVisible = false
})
//Display trending movies
//loadstate is of type combined loadstates, which combines the loadstate of different scenarios(when we refresh dataset or when we append new data to it) into this one object
//We can use it to check for these scenarios and make our views visible or unvisible according to it
setHasOptionsMenu(true)
}
override fun onItemClick(movie: MoviesResults.Movies) {
val action = MoviesListFragmentDirections.actionMoviesListFragmentToMoviesDetailsFragment(movie)
findNavController().navigate(action)
}
override fun onFavoriteClick(favorites: MoviesFavorites) {
daoViewModel.addMovieToFavs(favorites)
}
override fun onDeleteClick(favorites: MoviesFavorites) {
daoViewModel.deleteMovieFromFavs(favorites)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
// Inflate the gallery menu
inflater.inflate(R.menu.menu_gallery, menu)
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
MoviesListAdapter.kt
package com.example.moviesapp.ui
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Toast
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.moviesapp.R
import com.example.moviesapp.databinding.MovieLayoutBinding
import com.example.moviesapp.network.MoviesFavorites
import com.example.moviesapp.network.MoviesResults
val IMAGE_BASE_URL = "https://image.tmdb.org/t/p/w500"
class MoviesListAdapter constructor(private val listener: OnItemClickListener) :
ListAdapter<MoviesResults.Movies, MoviesListAdapter.MoviesListViewHolder>(DiffCallback) {
private lateinit var fav: MoviesFavorites
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MoviesListViewHolder {
val binding = MovieLayoutBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return MoviesListViewHolder(binding)
}
override fun onBindViewHolder(holder: MoviesListViewHolder, position: Int) {
val currentItem = getItem(position)
holder.binding.favoritesCheckbox.isChecked = currentItem.isFavorite
holder.binding.favoritesCheckbox.setOnCheckedChangeListener { _, isChecked ->
currentItem.isFavorite
}
if(holder.binding.favoritesCheckbox.isChecked ) {
currentItem.isFavorite = true
}
if (currentItem != null) {
holder.bind(currentItem)
}
}
inner class MoviesListViewHolder(val binding: MovieLayoutBinding) :
RecyclerView.ViewHolder(binding.root) {
init {
binding.root.setOnClickListener {
val position = absoluteAdapterPosition
if (position != RecyclerView.NO_POSITION) {
val item = getItem(position)
listener.onItemClick(item)
}
}
}
init {
binding.favoritesCheckbox.setOnClickListener{
if(binding.favoritesCheckbox.isChecked) {
val position = absoluteAdapterPosition
if (position != RecyclerView.NO_POSITION) {
val item = getItem(position)
item.isFavorite = true
fav = MoviesFavorites(item.title, item.id, item.release_date, item.overview, item.vote_average, item.poster_path, item.original_language, item.isFavorite)
listener.onFavoriteClick(fav)
listener.onCheckboxClick(binding.favoritesCheckbox.isChecked)
}
showToast("${fav.title} is added to your favorites")
}
else {
val position = absoluteAdapterPosition
if (position != RecyclerView.NO_POSITION) {
val item = getItem(position)
item.isFavorite = false
fav = MoviesFavorites(item.title, item.id, item.release_date, item.overview, item.vote_average, item.poster_path, item.original_language, item.isFavorite)
listener.onDeleteClick(fav)
listener.onCheckboxClick(binding.favoritesCheckbox.isChecked)
}
showToast("${fav.title} is removed from your favorites")
}
}
}
fun bind(movie: MoviesResults.Movies) {
binding.apply {
movieTitle.text = movie.title
movieRating.text = movie.vote_average
movieYear.text = movie.release_date
Glide.with(itemView)
.load(IMAGE_BASE_URL + movie.poster_path)
.centerCrop()
.error(R.drawable.ic_baseline_error_outline_24)
.into(movieImage)
val item = getItem(absoluteAdapterPosition)
favoritesCheckbox.isChecked = item.isFavorite
}
}
private fun showToast(string: String) {
Toast.makeText(itemView.context, string, Toast.LENGTH_SHORT).show()
}
}
interface OnItemClickListener {
fun onItemClick(movie: MoviesResults.Movies)
fun onFavoriteClick(favorites: MoviesFavorites)
fun onDeleteClick(favorites: MoviesFavorites)
fun onCheckboxClick(fav: Boolean)
}
companion object DiffCallback : DiffUtil.ItemCallback<MoviesResults.Movies>() {
override fun areItemsTheSame(
oldItem: MoviesResults.Movies,
newItem: MoviesResults.Movies
): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(
oldItem: MoviesResults.Movies,
newItem: MoviesResults.Movies
): Boolean {
return oldItem == newItem
}
}
}
MoviesDetailsFragment.kt
package com.example.moviesapp.ui.Fragments
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.navArgs
import com.bumptech.glide.Glide
import com.example.moviesapp.R
import com.example.moviesapp.databinding.FragmentMoviesDetailsBinding
import com.example.moviesapp.network.MoviesFavorites
import com.example.moviesapp.network.MoviesResults
import com.example.moviesapp.ui.DaoViewModel
import com.example.moviesapp.ui.IMAGE_BASE_URL
import com.example.moviesapp.ui.SharedViewModel
import dagger.hilt.android.AndroidEntryPoint
#AndroidEntryPoint
class MoviesDetailsFragment() : Fragment(R.layout.fragment_movies_details) {
//We can get the movies from the args property
private val args by navArgs<MoviesDetailsFragmentArgs>()
private val daoViewModel by viewModels<DaoViewModel>()
private val sharedViewModel by viewModels<SharedViewModel>()
private fun showToast(string: String) {
Toast.makeText(view?.context, string, Toast.LENGTH_SHORT).show()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val binding = FragmentMoviesDetailsBinding.bind(view)
sharedViewModel.checkBox.observe(viewLifecycleOwner) {
binding.favCheckbox.isChecked = it
}
binding.apply {
val movie: MoviesResults.Movies = args.movie
val fav = MoviesFavorites(
movie.title,
movie.id,
movie.release_date,
movie.overview,
movie.vote_average,
movie.poster_path,
movie.original_language,
movie.isFavorite,
)
//When you are in fragment/activity, pass it to a glide.with because view is less efficient
Glide.with(this#MoviesDetailsFragment)
.load(IMAGE_BASE_URL + movie.poster_path)
//Have the textview visible only when image is visible
.error(R.drawable.ic_baseline_error_outline_24)
.fitCenter()
.into(coverPhoto)
title.text = movie.title
releaseDate.text = movie.release_date
language.text = movie.original_language
rating.text = movie.vote_average
plot.text = movie.overview
favCheckbox.setOnClickListener {
if (favCheckbox.isChecked) {
fav.isFavorite = true
daoViewModel.addMovieToFavs(fav)
showToast("${fav.title} is added to your favorites")
} else {
fav.isFavorite = false
daoViewModel.deleteMovieFromFavs(fav)
showToast("${fav.title} is removed from your favorites")
}
}
}
}
}
SharedViewModel.kt
package com.example.moviesapp.ui
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
class SharedViewModel: ViewModel() {
val checkBox = MutableLiveData<Boolean>()
fun sendValue(favorite: Boolean) {
checkBox.value = favorite
}
class SharedViewModelFactor(
) : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(SharedViewModel::class.java)) {
#Suppress("UNCHECKED_CAST")
return SharedViewModel() as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}
}
You can user 2 methods to do so:
1 ) You can use LocalBroadcast to notify one fragment/activity of change in another.
Note: LocalBroadcast in now deprecated. Alternatively you can use eventbus to communication between fragments
Create a local Broadcast
private BroadcastReceiver onNotice= new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// intent can contain anydata
Log.d(TAG,"onReceive called");
}
};
Register your receiver in onResume of fragment like:
public void onResume() {
super.onResume();
IntentFilter iff= new IntentFilter(MyIntentService.ACTION);
LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, iff);
}
unRegister receiver in onPause:
public void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(onNotice);
}
For more information can you can refer to:
https://blog.mindorks.com/using-localbroadcastmanager-in-android
2 ) You can use LiveData to observe data changes of one fragment in another
Create shared ViewModel
public class SharedViewModel extends ViewModel {
private MutableLiveData<String> name;
public void setNameData(String nameData) {
name.setValue(nameData);
}
public MutableLiveData<String> getNameData() {
if (name == null) {
name = new MutableLiveData<>();
}
return name;
}
}
Fragment One
private SharedViewModel sharedViewModel;
public FragmentOne() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedViewModel = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sharedViewModel.setNameData(submitText.getText().toString());
}
});
}
Fragment Two
private SharedViewModel sharedViewModel;
public FragmentTwo() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedViewModel = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
sharedViewModel.getNameData().observe(this, nameObserver);
}
Observer<String> nameObserver = new Observer<String>() {
#Override
public void onChanged(String name) {
receivedText.setText(name);
}
};
For more details on viewmodel you can refer to :
https://nabeelj.medium.com/android-how-to-share-data-between-fragments-using-viewmodel-and-livedata-android-mvvm-9fc463af5152
https://developer.android.com/guide/fragments/communicate#fragments

Error: requestHandler has not been initialized

This project is a recycler view fragment that gets images from flickr and display it.
I used loopers and handlers to communicate between the recycler fragment and the downloading thumbnail fragment... I'm using Android Studio Bumblebee...
I’m facing an error with requestHandler… Maybe i’m not seeing a specific issue. but i checked the code several times but couldn’t find the missing part…
I get this error:
kotlin.UninitializedPropertyAccessException: lateinit property requestHandler has not been initialized at com.bignerdranch.android.photogallery.ThumbnailDownloader.queueThumbnail(ThumbnailDownloader.kt:94)
it is referring to this one…
fun queueThumbnail(target: T, url: String){ //page 510
Log.i(TAG, "Got a URL: $url")
requestMap[target] = url //page 521
requestHandler.obtainMessage(MESSAGE_DOWNLOAD, target)
.sendToTarget()
}
this code is being called by the Recyclerview from another fragment
override fun onBindViewHolder(holder: PhotoHolder, position: Int) {
val galleryItem = galleryItems[position]
//holder.bindTitle(galleryItem.title)
val placeholder: Drawable = ContextCompat.getDrawable(
requireContext(),
R.drawable.hala_atamleh
)?: ColorDrawable()
holder.bindTitle(placeholder) //should be bindDrawable but it didn't work
--> thumbnailDownloader.queueThumbnail(holder, galleryItem.url) //page 515
}
as far as i know, i Initialized it here:
#Suppress("UNCHECKED_CAST") //page 522
#SuppressLint("HandlerLeak")
override fun onLooperPrepared() {
requestHandler = object : Handler(Looper.getMainLooper()){
override fun handleMessage(msg: Message) {
if (msg.what == MESSAGE_DOWNLOAD){
val target = msg.obj as T
Log.i(TAG, "Got a request for URL: ${requestMap[target]}")
handleRequest(target)
}
}
}
}
what did i missed to get this error?
here is the file code:
import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import android.os.Message
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import java.util.concurrent.ConcurrentHashMap
private const val TAG = "ThumbnailDownloader"
private const val MESSAGE_DOWNLOAD = 0
class ThumbnailDownloader<in T>(private val responseHandler: Handler, //page. 524
private val onThumbnailDownloaded : (T, Bitmap) -> Unit)
: HandlerThread(TAG) /*, LifecycleObserver page 512*/ { //page. 510
private lateinit var requestHandler: Handler //page516++
private var hasQuit = false
private val requestMap = ConcurrentHashMap<T, String>()
private val flickrFetchr = FlickrFetchr()
val fragmentLifecycleObserver: LifecycleObserver = //page 527
object : LifecycleObserver{
#OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun setup() {
Log.i(TAG, "Starting background thread")
start() //page 514
looper
}
#OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun tearDown() {
Log.i(TAG, "Destroying background thread")
quit()
}
}
#Suppress("UNCHECKED_CAST") //page 522
#SuppressLint("HandlerLeak")
override fun onLooperPrepared() {
requestHandler = object : Handler(Looper.getMainLooper()){
override fun handleMessage(msg: Message) {
if (msg.what == MESSAGE_DOWNLOAD){
val target = msg.obj as T
Log.i(TAG, "Got a request for URL: ${requestMap[target]}")
handleRequest(target)
}
}
}
}
//page 528
val viewLifecycleObserver : LifecycleObserver =
object : LifecycleObserver {
#OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun tearDown(){
Log.i(TAG, "Clearing all requests from Queue")
requestHandler.removeMessages(MESSAGE_DOWNLOAD)
requestMap.clear()
}
}
override fun quit(): Boolean {
hasQuit = true
return super.quit()
}
fun queueThumbnail(target: T, url: String){ //page 510
Log.i(TAG, "Got a URL: $url")
requestMap[target] = url //page 521
requestHandler.obtainMessage(MESSAGE_DOWNLOAD, target)
.sendToTarget()
}
fun clearQueue() {
requestHandler.removeMessages(MESSAGE_DOWNLOAD)
requestMap.clear()
}
private fun handleRequest(target: T){
val url = requestMap[target] ?: return
val bitmap = flickrFetchr.fetchPhoto(url) ?: return
responseHandler.post(Runnable { //page.526
if(requestMap[target] != url || hasQuit){
return#Runnable
}
requestMap.remove(target)
onThumbnailDownloaded(target, bitmap)
})
}
}
PHOTOGalleryFragment:
package com.bignerdranch.android.photogallery
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
private lateinit var photoRecyclerView : RecyclerView
private lateinit var photoGalleryViewModel: PhotoGalleryViewModel
private lateinit var thumbnailDownloader: ThumbnailDownloader<PhotoGalleryFragment.PhotoHolder> //it should be PhotoHolder not Type or Handler
private const val TAG = "PhotoGalleryFragment"
class PhotoGalleryFragment:Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
retainInstance = true //page 511
photoGalleryViewModel = //page 494
ViewModelProvider(this).get(PhotoGalleryViewModel::class.java)
//thumbnailDownloader = ThumbnailDownloader() //p.513
val responseHandler = Handler(Looper.getMainLooper())//page 525
thumbnailDownloader =
ThumbnailDownloader(responseHandler){ photoHolder, bitmap ->
val drawable = BitmapDrawable(resources, bitmap)
photoHolder.bindDrawable(drawable)
}
lifecycle.addObserver(thumbnailDownloader.viewLifecycleObserver)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
viewLifecycleOwner.lifecycle.addObserver( //page. 529
thumbnailDownloader.viewLifecycleObserver
)
val view = inflater.inflate(R.layout.fragment_photo_gallery, container, false)
photoRecyclerView = view.findViewById(R.id.photo_recycler_view)
photoRecyclerView.layoutManager = GridLayoutManager(context,3)
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
photoGalleryViewModel.galleryItemLiveData.observe(
viewLifecycleOwner,
Observer { galleryItems ->
Log.d(TAG,"Have gallery items from ViewModel $galleryItems" )
photoRecyclerView.adapter = PhotoAdapter(galleryItems)
}
)
}
class PhotoHolder(private val itemImageView: ImageView)
: RecyclerView.ViewHolder(itemImageView){ //page 496
val bindDrawable: (Drawable) -> Unit = itemImageView::setImageDrawable
}
private inner class PhotoAdapter(private val galleryItems: List<GalleryItem>)
:RecyclerView.Adapter<PhotoHolder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PhotoHolder {
val view = layoutInflater.inflate(
R.layout.list_item_gallery,
parent,
false) as ImageView
return PhotoHolder(view)
}
override fun onBindViewHolder(holder: PhotoHolder, position: Int) {
val galleryItem = galleryItems[position]
//holder.bindTitle(galleryItem.title)
val placeholder: Drawable = ContextCompat.getDrawable(
requireContext(),
R.drawable.hala_atamleh
)?: ColorDrawable()
holder.bindDrawable(placeholder)
thumbnailDownloader.queueThumbnail(holder, galleryItem.url) //page 515
}
override fun getItemCount(): Int = galleryItems.size
}
companion object{
fun newInstance() = PhotoGalleryFragment()
}
override fun onDestroyView() { //page 530
super.onDestroyView()
thumbnailDownloader.clearQueue()
viewLifecycleOwner.lifecycle.removeObserver(
thumbnailDownloader.viewLifecycleObserver
)
}
override fun onDestroy() {
super.onDestroy()
lifecycle.removeObserver(
thumbnailDownloader.fragmentLifecycleObserver
)
}
}
I solved it in 2 steps
1- made requesthandler nullable... thanks to #Tenfour04
2- made the gallery this way
package com.bignerdranch.android.photogallery
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
private const val TAG = "PhotoGalleryFragment"
class PhotoGalleryFragment : Fragment() {
private lateinit var photoGalleryViewModel: PhotoGalleryViewModel
private lateinit var photoRecyclerView: RecyclerView
private lateinit var thumbnailDownloader: ThumbnailDownloader<PhotoHolder>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
retainInstance = true
photoGalleryViewModel =
ViewModelProviders.of(this).get(PhotoGalleryViewModel::class.java)
val responseHandler = Handler()
thumbnailDownloader =
ThumbnailDownloader(responseHandler) { photoHolder, bitmap ->
val drawable = BitmapDrawable(resources, bitmap)
photoHolder.bindDrawable(drawable)
}
lifecycle.addObserver(thumbnailDownloader.fragmentLifecycleObserver)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
viewLifecycleOwner.lifecycle.addObserver(
thumbnailDownloader.viewLifecycleObserver
)
val view = inflater.inflate(R.layout.fragment_photo_gallery, container, false)
photoRecyclerView = view.findViewById(R.id.photo_recycler_view)
photoRecyclerView.layoutManager = GridLayoutManager(context, 3)
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
photoGalleryViewModel.galleryItemLiveData.observe(
viewLifecycleOwner,
Observer { galleryItems ->
Log.d(TAG, "Have gallery items from view model $galleryItems")
photoRecyclerView.adapter = PhotoAdapter(galleryItems)
})
}
override fun onDestroyView() {
super.onDestroyView()
thumbnailDownloader.clearQueue()
viewLifecycleOwner.lifecycle.removeObserver(
thumbnailDownloader.viewLifecycleObserver
)
}
override fun onDestroy() {
super.onDestroy()
lifecycle.removeObserver(
thumbnailDownloader.fragmentLifecycleObserver
)
}
private class PhotoHolder(private val itemImageView: ImageView) : RecyclerView.ViewHolder(itemImageView) {
val bindDrawable: (Drawable) -> Unit = itemImageView::setImageDrawable
}
private inner class PhotoAdapter(private val galleryItems: List<GalleryItem>) :
RecyclerView.Adapter<PhotoHolder>() {
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): PhotoHolder {
val view = layoutInflater.inflate(
R.layout.list_item_gallery,
parent,
false
) as ImageView
return PhotoHolder(view)
}
override fun getItemCount(): Int = galleryItems.size
override fun onBindViewHolder(holder: PhotoHolder, position: Int) {
val galleryItem = galleryItems[position]
val placeholder: Drawable = ContextCompat.getDrawable(
requireContext(),
R.drawable.bill_up_close
) ?: ColorDrawable()
holder.bindDrawable(placeholder)
thumbnailDownloader.queueThumbnail(holder, galleryItem.url)
}
}
companion object {
fun newInstance() = PhotoGalleryFragment()
}
}

Writing a hash map into a firebase using kotlin though recycler adapter by implementing an interface in the recycleradapter

I want to write a hashmap into my firebase using the click listener which I have implemented in the fragment which acts only if one of the items is selected. but I get an error that I haven't got anytime before.
The logcat shows:
java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
at java.util.ArrayList.get(ArrayList.java:437)
at com.reazon.foodrunner.adapter.MenuRecyclerAdapter$MenuViewHolder$bind$1$1.onDataChange(MenuRecyclerAdapter.kt:104)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)
at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
this is my adapter :
package com.reazon.foodrunner.adapter
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.RelativeLayout
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.*
import com.reazon.foodrunner.R
import com.reazon.foodrunner.fragment.CartFragment
import com.reazon.foodrunner.model.MenuItem
class MenuRecyclerAdapter(
val context: Context,
private val btnProceedToCart: Button,
private val proceedToCartPassed: RelativeLayout,
private val menuList: List<MenuItem>,
private val listener: ContentListener
) : RecyclerView.Adapter<MenuRecyclerAdapter.MenuViewHolder>() {
private var goToCart: Int = 0
private var itemSelected: Int = 0
private var itemNumber: Int = 0
private var itemSelectedId = arrayListOf<String>()
private var itemSelectedName = arrayListOf<String>()
lateinit var proceedToCartLayout: RelativeLayout
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MenuViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.recycler_menu_single_row, parent, false)
return MenuViewHolder(view)
}
override fun getItemCount(): Int {
return menuList.size
}
override fun onBindViewHolder(holder: MenuViewHolder, position: Int) {
val menuItemItem = menuList[position]
holder.menuItemName.text = menuItemItem.item.toString()
proceedToCartLayout = proceedToCartPassed
btnProceedToCart.setOnClickListener {
Toast.makeText(context, "Proceeding To Cart", Toast.LENGTH_SHORT).show()
}
holder.btnMenuItem.setOnClickListener {
if (holder.btnMenuItem.text.toString() == "Remove") {
itemSelected--
holder.btnMenuItem.text = "ADD"
itemSelectedId.remove(holder.btnMenuItem.toString())
itemSelectedName.remove(holder.menuItemName.toString())
holder.btnMenuItem.setBackgroundResource(R.drawable.btn_menu_add_background)
} else {
itemSelected++
holder.btnMenuItem.text = "Remove"
itemSelectedId.add(holder.btnMenuItem.toString())
itemSelectedName.add(holder.menuItemName.toString())
holder.btnMenuItem.setBackgroundResource(R.drawable.btn_menu_remove_background)
}
if (itemSelected > 0) {
proceedToCartLayout.visibility = View.VISIBLE
} else {
proceedToCartLayout.visibility = View.INVISIBLE
}
print("$goToCart")
holder.btnMenuItem.tag = menuItemItem.id
itemNumber = position + 1
Log.d("Restaurant", "" + holder.menuItemName.text)
}
holder.btnMenuItem.tag = menuItemItem.id.toString() + ""
holder.bind(itemSelectedId, itemSelectedName, btnProceedToCart, listener)
}
class MenuViewHolder(view: View) : RecyclerView.ViewHolder(view) {
fun bind(menuSelectedId: List<String>, menuList: List<String>, btnProceedToCart: Button, listener: ContentListener) {
btnProceedToCart.setOnClickListener {
val mReference = FirebaseDatabase.getInstance().reference.child("Orders")
.child(FirebaseAuth.getInstance().currentUser!!.uid)
mReference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
val orderHashMap = HashMap<String, Any>()
for (item in 1..menuList.size) {
orderHashMap["id"] = menuSelectedId[item]
orderHashMap["item"] = menuList[item]
orderHashMap["cost"] = 200
orderHashMap["placed"] = true
}
mReference.updateChildren(orderHashMap)
}
override fun onCancelled(error: DatabaseError) {
Log.d("MenuRecyclerAdapter", error.message)
}
})
listener.openCart()
}
}
val menuItemName: TextView = view.findViewById(R.id.menuItemName)
val btnMenuItem: Button = view.findViewById(R.id.btnMenuAdd)
}
interface ContentListener {
fun openCart()
}
}
this is my menu fragment:
package com.reazon.foodrunner.fragment
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.RelativeLayout
import androidx.core.os.bundleOf
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.database.*
import com.reazon.foodrunner.R
import com.reazon.foodrunner.adapter.MenuRecyclerAdapter
import com.reazon.foodrunner.model.MenuItem
import com.reazon.foodrunner.model.Restaurant
import kotlinx.android.synthetic.main.fragment_menu.*
import kotlinx.android.synthetic.main.recycler_home_single_row.*
import kotlinx.android.synthetic.main.recycler_menu_single_row.*
class MenuFragment : Fragment(),MenuRecyclerAdapter.ContentListener{
private var menuRecyclerAdapter: MenuRecyclerAdapter? = null
private lateinit var menuReference: DatabaseReference
private var recyclerMenu: RecyclerView? = null
internal var menuItemList: MutableList<MenuItem> = ArrayList()
private var layoutManager: RecyclerView.LayoutManager? = null
private lateinit var proceedToCartLayout:RelativeLayout
private lateinit var btnProceedToCart: Button
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_menu, container, false)
menuReference = FirebaseDatabase.getInstance().reference.child("Menu")
recyclerMenu = view.findViewById(R.id.recyclerMenu)
btnProceedToCart = view.findViewById(R.id.btnGoToCart)
proceedToCartLayout = view.findViewById(R.id.rlProceedToCart)
// val restaurant = (Restaurant::class.java)
layoutManager = LinearLayoutManager(activity)
recyclerMenu!!.layoutManager = layoutManager
retrieveMenu()
return view
}
private fun retrieveMenu() {
menuItemList.clear()
menuReference.addValueEventListener(object : ValueEventListener {
override fun onCancelled(error: DatabaseError) {
Log.d("ERROR", "" + error.message)
}
override fun onDataChange(snapshot: DataSnapshot) {
for (p0 in snapshot.children) {
val menu = p0.getValue(MenuItem::class.java)
menuRecyclerAdapter = MenuRecyclerAdapter(context!!, btnProceedToCart, proceedToCartLayout,menuItemList,this#MenuFragment)//,this#MenuFragment)
recyclerMenu!!.adapter = menuRecyclerAdapter
if (menu != null) {
menuItemList.add(menu)
}
}
}
})
}
fun onBackPressed() {
when (this.fragmentManager?.findFragmentById(R.id.frame)) {
!is HomeFragment -> openHome()
}
}
private fun openHome() {
val transaction = fragmentManager?.beginTransaction()
transaction?.replace(R.id.frame, HomeFragment())
transaction?.commit()
}
override fun openCart() {
val transaction = fragmentManager?.beginTransaction()
transaction?.replace(R.id.frame, CartFragment())
transaction?.commit()
}
}
although I haven't made the cart fragment and recycler properly, this is my cart fragment:
package com.reazon.foodrunner.fragment
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.reazon.foodrunner.R
import com.reazon.foodrunner.activity.FinishActivity
import com.reazon.foodrunner.adapter.CartRecyclerAdapter
import com.reazon.foodrunner.model.Order
import kotlinx.android.synthetic.main.fragment_cart.*
class CartFragment : Fragment() {
lateinit var btnCheckout:Button
private var recyclerCart:RecyclerView? = null
private var recyclerAdapter:CartRecyclerAdapter? = null
private var layoutManager:RecyclerView.LayoutManager? = null
private var orderList:MutableList<Order> = ArrayList()
private var cartDatabaseReference:DatabaseReference? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_cart, container, false)
btnCheckout = view.findViewById(R.id.btnCheckout)
val firebaseUid = FirebaseAuth.getInstance().currentUser!!.uid
cartDatabaseReference = FirebaseDatabase.getInstance().reference.child("Orders").child(firebaseUid)
layoutManager =LinearLayoutManager(activity)
recyclerCart = view.findViewById(R.id.recyclerCart)
recyclerCart!!.layoutManager = layoutManager
btnCheckout.setOnClickListener {
val intent = Intent(activity, FinishActivity::class.java )
startActivity(intent)
}
return view
}
}
Cart adapter:
package com.reazon.foodrunner.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.reazon.foodrunner.R
import com.reazon.foodrunner.model.Order
import kotlinx.android.synthetic.*
import kotlinx.android.synthetic.main.recycler_cart_single_row.view.*
import java.util.function.ToDoubleBiFunction
class CartRecyclerAdapter(
val context: Context,
private val orderList:List<Order>
):RecyclerView.Adapter<CartRecyclerAdapter.CartViewHolder>() {
class CartViewHolder(view: View):RecyclerView.ViewHolder(view){
val txtItemName:TextView = view.findViewById(R.id.txtItemNameCart)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CartViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.recycler_cart_single_row,parent,false)
return CartViewHolder(view)
}
override fun onBindViewHolder(holder: CartViewHolder, position: Int) {
val order = orderList[position]
holder.txtItemName.text = order.item
}
override fun getItemCount(): Int {
return orderList.size
}
}
I am unable to understand what to do here to simply upload the hash map of orders and retrieve them.
it was a simple error as I was using the index (indices) in the wrong manner as it should have been
for (item in menuList.indices) {
orderHashMap["id"] = menuSelectedId[item]
orderHashMap["item"] = menuList[item]
orderHashMap["cost"] = 200
orderHashMap["placed"] = true
}
and the list got the correct index of each element thereafter, and hashmap was written to firebase.

Categories

Resources