Passing data from recyclerview to details activity (kotlin, firebase) - android

I'm writing an app which allows you to set up a hairdresser appointment. I'm storing the data about the visits in firebase database. I'm trying to implement a recyclerview with onclick listener which displays date in recycler cardview and displays new activity with details after being clicked. I have a problem with passing data to this details activity. App crashes after recycler is clicked and the main error I get is
java.lang.RuntimeException: Parcelable encountered IOException writing
serializable object
What might be the reason?
This is how the database looks like:
OrderForm.class
package com.example.barberqueue.db
import com.example.barberqueue.SummaryViewModel
import java.io.Serializable
import java.util.ArrayList
class OrderForm(
val date: String? = null,
val hour: String? = null,
val isAccepted: Boolean = false,
val isCanceled: Boolean = false,
val isDone: Boolean = false,
val price: Float = 0f,
val services: ArrayList<SummaryViewModel>? = null,
val servicesTime: Int = 0,
val userId: String? = null
): Serializable {}
AppointmentsAdapter.kt
package com.example.barberqueue.adapters
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.barberqueue.R
import com.example.barberqueue.db.OrderForm
import com.example.barberqueue.interfaces.OrderClickView
class AppointmentsAdapter(
private val appointmentsList: ArrayList<OrderForm>, private val orderClickView: OrderClickView
) :
RecyclerView.Adapter<AppointmentsAdapter.AppointmentsViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AppointmentsViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(
R.layout.appointments_view_itemview,
parent, false
)
return AppointmentsViewHolder(itemView)
}
override fun onBindViewHolder(holder: AppointmentsViewHolder, position: Int) {
val currentItem = appointmentsList[position]
holder.date.text = currentItem.date
holder.itemView.setBackgroundColor(Color.parseColor("#00ffffff"))
holder.itemView.setOnClickListener {
orderClickView.onClickOrder(appointmentsList[position], holder.bindingAdapterPosition)
}
}
override fun getItemCount(): Int {
return appointmentsList.size
}
class AppointmentsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val date: TextView = itemView.findViewById(R.id.appointment_date)
}
}
Dashboard.kt (where the recycler is displayed)
package com.example.barberqueue
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.barberqueue.adapters.AppointmentsAdapter
import com.example.barberqueue.databinding.DashboardBinding
import com.example.barberqueue.db.OrderForm
import com.example.barberqueue.interfaces.OrderClickView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.database.*
import com.google.firebase.ktx.Firebase
class Dashboard : AppCompatActivity(), OrderClickView {
private var x1: Float = 0F
private var y1: Float = 0F
private var x2: Float = 0F
private var y2: Float = 0F
private lateinit var database: DatabaseReference
private lateinit var orderArrayList: ArrayList<OrderForm>
private lateinit var auth: FirebaseAuth
private lateinit var binding: DashboardBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DashboardBinding.inflate(layoutInflater)
setContentView(binding.root)
database = FirebaseDatabase.getInstance().reference
auth = FirebaseAuth.getInstance()
findViewById<Button>(R.id.add_new_visit_btn)
binding.addNewVisitBtn.setOnClickListener { openActivityNewVisit() }
binding.accMngBtn.setOnClickListener { openActivityAccountManagement() }
binding.logoutBtn.setOnClickListener {
Firebase.auth.signOut()
finish()
openActivityMainActivity()
}
binding.logo.setOnClickListener {
openActivityContact()
}
binding.appointmentsView.layoutManager = LinearLayoutManager(this)
binding.appointmentsView.setHasFixedSize(true)
orderArrayList = arrayListOf<OrderForm>()
getData()
}
override fun onClickOrder(order: OrderForm, position: Int) {
val intent= Intent(this, ViewAppointment::class.java)
intent.putExtra("order", order)
startActivity(intent)
}
private fun getData() {
database = FirebaseDatabase.getInstance().getReference("FutureAppointment")
database.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
//Log.w("TAG", "app_added1")
for (appointmentSnapshot in snapshot.children) {
val appointment = appointmentSnapshot.getValue(OrderForm::class.java)
if (appointment != null) {
if (appointment.userId == auth.currentUser?.uid /*oraz data jest w przyszłości lub dzisiejsza*/) {
orderArrayList.add(appointment)
//Log.w("TAG", "app_added")
}
}
}
binding.appointmentsView.adapter = AppointmentsAdapter(orderArrayList, this#Dashboard)
}
}
override fun onCancelled(error: DatabaseError) {
Log.w("TAG", "loadPost:onCancelled")
}
})
}
private fun openActivityMainActivity() {
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
}
private fun openActivityContact() {
val intent = Intent(this, ContactData::class.java)
startActivity(intent)
}
private fun changingTabs(position: Int) {
if (position == 0) {
}
if (position == 1) {
}
}
//funkcja do poruszania sie po ui w poziomie
override fun onTouchEvent(touchEvent: MotionEvent): Boolean {
when (touchEvent.action) {
MotionEvent.ACTION_DOWN -> {
x1 = touchEvent.x
y1 = touchEvent.y
}
MotionEvent.ACTION_UP -> {
x2 = touchEvent.x
y2 = touchEvent.y
if (x1 < x2 && y1 <= y2 + 100 && y1 >= y2 - 100) {
openActivityMenu()
Log.e("position", "$x1,$y1 $x2,$y2")
} else if (x1 > x2 && y1 <= y2 + 100 && y1 >= y2 - 100) {
openActivitySTH()
Log.e("position", "$x1,$y1 $x2,$y2")
}
}
}
return false
}
private fun openActivityAccountManagement() {
val intent = Intent(this, AccountManagement::class.java)
startActivity(intent)
}
private fun openActivityMenu() {
val intent = Intent(this, Menu::class.java)
startActivity(intent)
}
private fun openActivitySTH() {
val intent = Intent(this, Right::class.java)
startActivity(intent)
}
private fun openActivityNewVisit() {
val intent = Intent(this, NewVisit::class.java)
startActivity(intent)
}
}
Interfaces.kt
package com.example.barberqueue.interfaces
import com.example.barberqueue.db.OrderForm
import com.google.firebase.firestore.auth.User
interface FromMakeAppointmentToSummary {
fun getSelectedTime(time: String)
}
interface OrderClickView{
fun onClickOrder(orderForm : OrderForm, position: Int)
}

I see there is an ArrayList of SummaryViewModel, is SummaryViewModel serializable?
Also...
I would not recommend passing viewModels to activities, rather stick to passing classes containing data instead of methods and consuming the data in the next activity.

Related

RecyclerView shows a list of copies of activity screen instead of data from database table

I am simply trying to setup the ClickListener for changing the user name. Google's tutorials emphasize fragments, which I will do later. Based on what I've seen in other examples and the Android documentation, I thought I had the View Binding set up properly. I don't have enough information to understand why I see a list of copies of the activity screen inside the RecyclerView.
UserListAdapter.kt
package com.neillbarrett.debitsandcredits
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.neillbarrett.debitsandcredits.database.UsersTable
import com.neillbarrett.debitsandcredits.databinding.ActivityManageUsersBinding
val inAdapter: String = "In UserListAdapter "
class UserListAdapter(private val userSelect: (UsersTable?) -> Unit) :
ListAdapter<UsersTable, UserListAdapter.UserViewHolder>(UsersComparator()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserListAdapter.UserViewHolder {
Log.w(inAdapter,"OnCreateViewHolder started")
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.activity_manage_users, parent, false)
return UserViewHolder.create(parent)
}
class UserViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(usersTable: UsersTable?, userSelect: (UsersTable?) -> Unit) {
Log.w(inAdapter,"UserViewHolder started")
itemView.setOnClickListener { View.OnClickListener {
/* if (View.) { }*/
val nameSelected = userSelect(usersTable)
//userSelect(usersTable)
//need to assign the result of the clicklistener to the editText
//binding.etEditName.setText(R.layout.activity_list_of_users.toString())
}}
}
companion object {
fun create(parent: ViewGroup) : UserViewHolder {
Log.w(inAdapter,"Companion object 'Create' function started")
val view: View = LayoutInflater.from(parent.context)
.inflate(R.layout.activity_manage_users, parent, false)
return UserViewHolder(view)
}
}
}
override fun onBindViewHolder(holder: UserViewHolder, position: Int) {
Log.w(inAdapter,"OnBindViewHolder started")
val current = getItem(position)
holder.bind(current, userSelect)
}
class UsersComparator : DiffUtil.ItemCallback<UsersTable>() {
override fun areItemsTheSame(oldItem: UsersTable, newItem: UsersTable): Boolean {
Log.w(inAdapter,"areItemsTheSame function started")
return oldItem == newItem
}
override fun areContentsTheSame(oldItem: UsersTable, newItem: UsersTable): Boolean {
Log.w(inAdapter,"areContentsTheSame function started")
return oldItem.userName == newItem.userName
}
}
}
ManageUsers.kt
package com.neillbarrett.debitsandcredits
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.activity.viewModels
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.neillbarrett.debitsandcredits.database.CreditsAndDebitsApp
import com.neillbarrett.debitsandcredits.database.UsersTable
import com.neillbarrett.debitsandcredits.databinding.ActivityManageUsersBinding
class ManageUsers : AppCompatActivity() {
lateinit var binding: ActivityManageUsersBinding
lateinit var recyclerView: RecyclerView
lateinit var editTextAddUser: EditText
lateinit var editTextChangeUser: EditText
lateinit var newUser: String
var userSelect: ((UsersTable?) -> Unit) = {}
var position: Long = 0
val inWhichActivity: String = "In ManageUsers"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityManageUsersBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
//setContentView(R.layout.activity_manage_users)
Log.w(inWhichActivity, "Setting up userViewModel & repository")
val userViewModel: UserViewModel by viewModels {
UserViewModelFactory((application as CreditsAndDebitsApp).repository)
}
recyclerView = findViewById(R.id.rec_view_userList)
editTextAddUser = findViewById(R.id.et_AddUser)
editTextChangeUser = findViewById(R.id.et_Edit_Name)
val adapter = UserListAdapter(userSelect)
binding.recViewUserList.adapter = adapter
recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
userViewModel.allUsers.observe(this, Observer() {user ->
Log.w(inWhichActivity,"Starting Observer")
user?.let { adapter.submitList(it) }
Log.w(inWhichActivity, "Started Observer")
})
val btnAddUser = findViewById<Button>(R.id.btn_AddUser)
btnAddUser.setOnClickListener {
Log.w(inWhichActivity,"Started btnAddUser.setOnClickListener")
if (TextUtils.isEmpty(editTextAddUser.text)) {
Toast.makeText(this, "User name cannot be empty", Toast.LENGTH_SHORT).show()
} else {
newUser = editTextAddUser.text.toString()
// Log.w("Add user button", "Username put into newUser")
userViewModel.insertUser(UsersTable(0, newUser))
// Toast.makeText(this, "Username added to table", Toast.LENGTH_SHORT).show()
// Log.w("Add user button", "Username added to table")
}
}
val btnChangeUser = findViewById<Button>(R.id.btn_ChangeUserName)
btnChangeUser.setOnClickListener {
Log.w(inWhichActivity,"Started btnChangeUser.setOnClickListener")
Toast.makeText(this, "Selected position is ${recyclerView.getChildAdapterPosition(it)}", Toast.LENGTH_SHORT).show()
/* if (recyclerView.getChildAdapterPosition(it) == -1) {
Toast.makeText(this, "Select a name.", Toast.LENGTH_SHORT).show()
} else {
if (editTextChangeUser.text.toString() == recyclerView.adapter.toString()) {
Toast.makeText(this, "Name has not been changed.", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Name would have been changed.", Toast.LENGTH_SHORT).show()
val rvItemRecId: Long
rvItemRecId = adapter.getItemId(position.toInt())
userViewModel.updateUser(UsersTable(rvItemRecId.toInt(), adapter.toString()))
}
}*/
}
}
}
UserViewModel.kt
package com.neillbarrett.debitsandcredits
import android.util.Log
import androidx.lifecycle.*
import com.neillbarrett.debitsandcredits.database.UsersTable
import kotlinx.coroutines.launch
import java.lang.IllegalArgumentException
val inViewModel: String = "In UserViewModel "
class UserViewModel(private val repository: UserRepository) : ViewModel() {
// Using LiveData and caching what allWords returns has several benefits:
// - We can put an observer on the data (instead of polling for changes) and only update the
// the UI when the data actually changes.
// - Repository is completely separated from the UI through the ViewModel.
val allUsers: LiveData<List<UsersTable>> = repository.allUsers.asLiveData()
/**
* Launching a new coroutine to insert the data in a non-blocking way
*/
fun insertUser(user: UsersTable) = viewModelScope.launch {
repository.insertUser(user)
Log.w(inViewModel,"insertUser called")
//repository.insertUser(usersTable = List<UsersTable>())
//repository.insertUser(UsersTable(0, userName = user.userName))
}
fun updateUser(user: UsersTable) = viewModelScope.launch {
repository.updateUser(user)
Log.w(inViewModel, "updateUser called")
}
fun deleteUser(user: UsersTable) = viewModelScope.launch {
repository.deleteUser(user)
Log.w(inViewModel, "deteUser called")
}
}
class UserViewModelFactory(private val repository: UserRepository) : ViewModelProvider.Factory{
override fun <T : ViewModel> create(modelClass: Class<T>): T {
Log.w(inViewModel,"UserViewModelFactory called")
if (modelClass.isAssignableFrom(UserViewModel::class.java)) {
#Suppress("UNCHECKED_CAST")
return UserViewModel(repository) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}

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)

How to define Imageview in getter setter method

Hello guy i am new to Kotlin android and working on a demo in this demo i am trying to get an image from the gallery and set it in my recyclerview but i am getting the solution requesting you to please find me a solution Thanks in Advance!!
This is my CustomAdapter.kt:-
package com.example.itemgetset
import android.app.Activity
import android.app.AlertDialog
import android.content.ContentValues.TAG
import android.content.Intent
import android.os.Build
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.PopupMenu
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.snackbar.Snackbar
#Suppress("UNREACHABLE_CODE")
class CustomAdapter(
private var activity: Activity,
private val userList: ArrayList<ProductInfoGetSet>,
private var isforlist: Boolean,
) :
RecyclerView.Adapter<CustomAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val itemview=
LayoutInflater.from(parent.context).inflate(R.layout.list_layout, parent, false)
return ViewHolder(itemview)
}
#RequiresApi(Build.VERSION_CODES.N)
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val productInfoGetSet: ProductInfoGetSet = userList[position]
holder.image = productInfoGetSet.image
holder.txtId.text = productInfoGetSet.id
holder.txtName.text = productInfoGetSet.name
holder.txtQuantity.text = productInfoGetSet.quantity
holder.txtPrice.text = productInfoGetSet.price
val id = userList[position].id
Log.e(TAG, "List item ID: $id")
holder.buttonViewOption.setOnClickListener {
val popup = PopupMenu(activity, holder.buttonViewOption)
popup.inflate(R.menu.pop_menu)
popup.setOnMenuItemClickListener { item ->
when (item.itemId) {
R.id.edit -> {
val intent = Intent(activity, AddDetails::class.java)
intent.putExtra("isFor", "Update")
intent.putExtra("id", productInfoGetSet.id)
intent.putExtra("image",productInfoGetSet.image)
intent.putExtra("name", productInfoGetSet.name)
intent.putExtra("quantity", productInfoGetSet.quantity)
intent.putExtra("price", productInfoGetSet.price)
activity.startActivity(intent)
}
R.id.delete -> {
val builder = AlertDialog.Builder(activity)
builder.setTitle("Delete")
builder.setMessage("Do you want to delete the item?")
builder.setPositiveButton("Yes") { _, _ ->
userList.removeAt(position)
notifyItemRemoved(position)
val snack = Snackbar
.make(
holder.linearly,
"Item was removed from the list.",
Snackbar.LENGTH_SHORT
)
snack.show()
}
builder.setNegativeButton("No") { _, _ ->
}
val dialog: AlertDialog = builder.create()
dialog.show()
}
}
false
}
popup.show()
}
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getItemCount(): Int {
return userList.size
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val txtName = itemView.findViewById(R.id.txt_name) as TextView
val txtId = itemView.findViewById(R.id.txt_id) as TextView
var image = itemView.findViewById(R.id.imageView2) as ImageView
val txtQuantity = itemView.findViewById(R.id.txt_quantity) as TextView
val txtPrice = itemView.findViewById(R.id.txt_price) as TextView
val linearly: LinearLayout = itemView.findViewById(R.id.linearlayout)
val buttonViewOption = itemView.findViewById<View>(R.id.txt_Options) as TextView
}
}
in this adapter i gent and error on holder.image = productInfoGetSet.image this line and not get solved.
This is my AddDeatils.kt:-
package com.example.itemgetset
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.os.Build
import android.os.Bundle
import android.os.Message
import android.provider.MediaStore
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import kotlinx.android.synthetic.main.add_item.*
import kotlinx.android.synthetic.main.list_layout.*
class AddDetails : AppCompatActivity() {
private lateinit var btnSubmit: Button
private lateinit var edtName: EditText
private lateinit var edtQuantity: EditText
private lateinit var edtPrice: EditText
private lateinit var imageview: ImageView
companion object {
private const val IMAGE_PICK_CODE = 1000
private const val PERMISSION_CODE = 1001
}
#SuppressLint("SetTextI18n", "ResourceType")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.add_item)
supportActionBar?.hide()
findViewById()
onclick()
if (intent.getStringExtra("isFor").equals("Update")) {
intent.getStringExtra("image")?.toInt()?.let { imageview.setImageResource(it) }
edtName.setText(intent.getStringExtra("name"))
edtQuantity.setText(intent.getStringExtra("quantity"))
edtPrice.setText(intent.getStringExtra("price"))
}
}
private fun findViewById() {
btnSubmit = findViewById(R.id.btn_submit)
edtName = findViewById(R.id.edt_name)
edtQuantity = findViewById(R.id.edt_quantity)
edtPrice = findViewById(R.id.edt_price)
imageview = findViewById(R.id.image_view)
}
#SuppressLint("ResourceType")
private fun onclick() {
btnSubmit.setOnClickListener {
when {
edtName.text.trim().isEmpty() -> {
edtName.error = "Please Enter Product Name"
Toast.makeText(
applicationContext,
"Please Enter Product Name",
Toast.LENGTH_SHORT
)
.show()
}
edtQuantity.text.trim().isEmpty() -> {
edtQuantity.error = "Please Enter Product Quantity"
Toast.makeText(
applicationContext,
"Please Enter Product Quantity",
Toast.LENGTH_SHORT
).show()
}
edtPrice.text.trim().isEmpty() -> {
edtPrice.error = "Please Enter Product Price"
Toast.makeText(
applicationContext,
"Please Enter Product Price",
Toast.LENGTH_SHORT
)
.show()
}
else -> {
Toast.makeText(
applicationContext,
"Product Added Successfully ",
Toast.LENGTH_SHORT
).show()
val temp = Temp()
temp.image = imageview.toString()
temp.name = edtName.text.toString()
temp.quantity = edtQuantity.text.toString()
temp.price = edtPrice.text.toString()
if (intent.getStringExtra("isFor").equals("Update")) {
temp.id = intent.getStringExtra("id").toString()
}
val message: Message = Message.obtain()
message.what = 111
message.obj = temp
MainActivity.handler.sendMessage(message)
finish()
}
}
}
imageview.setOnClickListener {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_DENIED
) {
val permissions = arrayOf(android.Manifest.permission.READ_EXTERNAL_STORAGE)
requestPermissions(permissions, PERMISSION_CODE)
} else {
pickImageFromGallery()
}
} else {
pickImageFromGallery()
}
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
when (requestCode) {
PERMISSION_CODE -> {
if (grantResults.isNotEmpty() && grantResults[0] ==
PackageManager.PERMISSION_GRANTED
) {
pickImageFromGallery()
} else {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show()
}
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
private fun pickImageFromGallery() {
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, IMAGE_PICK_CODE)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode == Activity.RESULT_OK && requestCode == IMAGE_PICK_CODE) {
imageview.setImageURI(data?.data)
super.onActivityResult(requestCode, resultCode, data)
}
}
}
And this is my MainActivity.kt:-
package com.example.itemgetset
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Button
import android.widget.GridView
import android.widget.LinearLayout
import android.widget.ListView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
#Suppress("DEPRECATION")
class MainActivity : AppCompatActivity() {
lateinit var activity: Activity
val userList = ArrayList<ProductInfoGetSet>()
private lateinit var btnProductAdd: Button
lateinit var llEmptyView: LinearLayout
lateinit var llMain: LinearLayout
private var listView: ListView? = null
private var gridView: GridView? = null
lateinit var recyclerView: RecyclerView
private lateinit var llFab: LinearLayout
private lateinit var linearLayoutManager: LinearLayoutManager
private lateinit var gridLayoutManager: GridLayoutManager
private lateinit var adapter: CustomAdapter
private var isforlist = true
companion object {
var handler: Handler = Handler()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
activity = this
initView()
onClicks()
setUpData()
handler = #SuppressLint("HandlerLeak")
object : Handler() {
override fun handleMessage(msg: Message) {
if (msg.what == 111) {
val temp: Temp = msg.obj as Temp
if (temp.id == "") {
userList.add(
ProductInfoGetSet(
(userList.size + 1).toString(),
temp.image,
temp.name,
temp.quantity,
temp.price,
)
)
adapter = CustomAdapter(activity, userList, isforlist)
recyclerView.adapter = adapter
} else {
for (i in userList.indices) {
if (userList[i].id == temp.id) {
userList[i].id = temp.id
userList[i].image = temp.image
userList[i].name = temp.name
userList[i].quantity = temp.quantity
userList[i].price = temp.price
}
}
adapter.notifyDataSetChanged()
}
}
if (userList.size > 0) {
llEmptyView.visibility = View.GONE
llMain.visibility = View.VISIBLE
} else {
llEmptyView.visibility = View.VISIBLE
llMain.visibility = View.GONE
}
}
}
}
private fun changeLayoutManager() {
if (recyclerView.layoutManager == linearLayoutManager) {
recyclerView.layoutManager = gridLayoutManager
} else {
recyclerView.layoutManager = linearLayoutManager
}
}
private fun initView() {
btnProductAdd = findViewById(R.id.btn_product_add)
llFab = findViewById(R.id.ll_fab)
llEmptyView = findViewById(R.id.llEmptyView)
listView = findViewById(R.id.list_product)
gridView = findViewById(R.id.list_productGV)
llMain = findViewById(R.id.llMain)
recyclerView = findViewById(R.id.recycler_view)
recyclerView.layoutManager = LinearLayoutManager(this)
linearLayoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
gridLayoutManager = GridLayoutManager(this, 2)
}
private fun onClicks() {
btnProductAdd.setOnClickListener {
val intent = Intent(this#MainActivity, AddDetails::class.java)
intent.putExtra("isFor", "Add")
startActivity(intent)
}
llFab.setOnClickListener {
val intent = Intent(this#MainActivity, AddDetails::class.java)
intent.putExtra("isFor", "Add")
startActivity(intent)
}
}
private fun setUpData() {
if (userList.size > 0) {
llEmptyView.visibility = View.GONE
llMain.visibility = View.VISIBLE
} else {
llEmptyView.visibility = View.VISIBLE
llMain.visibility = View.GONE
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.menu_view) {
if (userList.size > 0) {
changeLayoutManager()
}
return true
}
return super.onOptionsItemSelected(item)
}
}
My ProductInfoGetSet.kt:-
package com.example.itemgetset
import android.widget.ImageView
class ProductInfoGetSet(
var id: String,
var image: ImageView,
var name: String,
var quantity: String,
var price: String
)
Temp.kt:-
package com.example.itemgetset
import android.widget.ImageView
class Temp {
var id: String = ""
var image: ImageView =
var name: String = ""
var quantity: String = ""
var price: String = ""
}
Thanks in advance!!
I understand you are new to Android. I will list down points below for you to understand clearly.
As a standard practice you must not use ImageView in any model as Model can only hold data.
Use databinding for views.
As suggested by Rupam Saini, you can use Glide or Picasso for image loading.
You can't pass imageView in bundle as it will create different object when you read it again. There is a chance of leaking context also.
Regarding your question
in this adapter i gent and error on holder.image = productInfoGetSet.image this line and not get solved.
You are trying to set an ImageView to another ImageView which is not correct. Temp file is incorrect, there is no value after = . So Temp file must also have error.
It'll be better if you show your ProductInfoGetSet class and the error logs.
You should not set the image directly
holder.image = productInfoGetSet.image
Instead you can get the image's URI and then set it like this
holder.image.setImageUri(imageUri)
If you are still getting issues then you can use the Glide library

How to change visibility of button in activity from activity recycler adapter

I want to change the visibility of "Proceed to card" button,
to visible when the user clicks on add button and back to invisible when all the items got removed :
Screenshot
VISIBILITY is set to INVISIBLE in layout
I have added a count variable to compare
RestaurantMenuRecyclerAdapter.kt
package com.himanshu.hungerhunt.adapter
import com.himanshu.hungerhunt.R
import com.himanshu.hungerhunt.model.FoodMenu
import com.himanshu.hungerhunt.databse.FoodEntity
import com.himanshu.hungerhunt.activity.RestaurantMenuActivity
import android.widget.Toast
import android.widget.Button
import android.widget.TextView
import android.view.View
import android.view.LayoutInflater
import android.view.ViewGroup
import android.content.Context
import android.content.SharedPreferences
import androidx.recyclerview.widget.RecyclerView
class RestaurantMenuRecyclerAdapter(val context: Context, private val itemList: ArrayList<FoodMenu>) :
RecyclerView.Adapter<RestaurantMenuRecyclerAdapter.RestaurantMenuViewHolder>() {
var total: Int = 0
var count = 0
class RestaurantMenuViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val txtFoodId: TextView = view.findViewById(R.id.txtFoodId)
val txtFoodName: TextView = view.findViewById(R.id.txtFoodName)
val txtFoodPrice: TextView = view.findViewById(R.id.txtFoodPrice)
val btnAddFood: Button = view.findViewById(R.id.btnAddToCart)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RestaurantMenuViewHolder {
val view =
LayoutInflater.from(parent.context).inflate(R.layout.recycler_food_item, parent, false)
return RestaurantMenuViewHolder(view)
}
override fun getItemCount(): Int {
return itemList.size
}
override fun onBindViewHolder(holder: RestaurantMenuViewHolder, position: Int) {
val foodMenu = itemList[position]
val foodName = foodMenu.foodName
val foodId = foodMenu.foodId
val foodPrice = foodMenu.foodPrice
holder.txtFoodId.text = (position + 1).toString()
holder.txtFoodName.text = foodMenu.foodName
holder.txtFoodPrice.text = foodMenu.foodPrice
val foodEntity = FoodEntity(foodId, foodName, foodPrice)
holder.btnAddFood.setOnClickListener {
val sharedPreferences: SharedPreferences =
context.getSharedPreferences("Cart Preferences", Context.MODE_PRIVATE)
if (!RestaurantMenuActivity.DBAsyncTask(context, foodEntity, 1).execute().get()) {
val async = RestaurantMenuActivity.DBAsyncTask(context, foodEntity, 2).execute()
val result = async.get()
if (result) {
Toast.makeText(context, "${holder.txtFoodName.text} Added", Toast.LENGTH_SHORT)
.show()
holder.btnAddFood.setBackgroundResource(R.color.lightOrange)
holder.btnAddFood.text = "Remove"
total += foodMenu.foodPrice.toInt()
count += 1
sharedPreferences.edit().putInt("total", total).apply()
} else {
Toast.makeText(context, "Error", Toast.LENGTH_SHORT).show()
}
} else {
val async = RestaurantMenuActivity.DBAsyncTask(context, foodEntity, 3).execute()
val result = async.get()
if (result) {
Toast.makeText(
context,
"${holder.txtFoodName.text} Removed",
Toast.LENGTH_SHORT
).show()
holder.btnAddFood.setBackgroundResource(R.color.materialRed)
holder.btnAddFood.text = "Add"
total -= foodMenu.foodPrice.toInt()
count -= 1
sharedPreferences.edit().putInt("total", total).apply()
} else {
Toast.makeText(context, "Error", Toast.LENGTH_SHORT).show()
}
}
}
}
}
I have tried this
RestaurantMenuActivity().btnProceedToCart.findViewById<View>(R.id.btnProceedToCart).visibility = View.VISIBLE
But it is not working
you can use interface that will notify you in your activity when click on addFood button in your adapter.
First, make the interface in your adapter.
class RestaurantMenuRecyclerAdapter(val context: Context, private val itemList:
ArrayList<FoodMenu>) :
RecyclerView.Adapter<RestaurantMenuRecyclerAdapter.RestaurantMenuViewHolder>() {
interface RestaurantMenuListener {
fun onAddClick()
}
}
Secondly, pass the interface in your adapter from the activity along with the other parameters that you are passing.
class RestaurantMenuRecyclerAdapter(val context: Context, private val itemList:
ArrayList<FoodMenu>,val mCallBack : RestaurantMenuistener) :
RecyclerView.Adapter<RestaurantMenuRecyclerAdapter.RestaurantMenuViewHolder>() {
interface RestaurantMenuistener {
fun onAddClick()
}
}
And in your activity,
adapter = RestaurantMenuRecyclerAdapter(context,itemlist, Object:
RestaurantMenuRecyclerAdapter.RestaurantMenuistener{
override fun onAddClick(){
//Do your stuff here like hide or show.
}
})
Finally, in your adapter when you click on add button,
holder.btnAddFood.setOnClickListener {
mCallback.onAddClick()
}

ViewModel updates on screen rotation

I've created a simple project to study Kotlin and Android architecture
https://github.com/AOreshin/shtatus
The screen consists of RecyclerView and three EditTexts.
Corresponding ViewModel is exposing 7 LiveData's:
Three LiveData corresponding to filters
Event to notify the user that no entries are found
Event to notify the user that no entries are present
Status of SwipeRefreshLayout
List of connections to show based on filter input
When user types text in filter ViewModel's LiveData gets notified about the changes and updates the data. I 've read that it's a bad practice to expose MutableLiveData to Activities/Fragments but they have to notify ViewModel about the changes somehow. When no entries are found based on the user's input Toast is shown.
The problem
When the user enters filter values that have no matches, Toast is shown. If the user then rotates the device Toast is shown again and again.
I've read these articles:
https://medium.com/androiddevelopers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150
https://proandroiddev.com/livedata-with-single-events-2395dea972a8
But I don't understand how I can apply these to my use case. I think the problem in how I perform the updates
private val connections = connectionRepository.allConnections()
private val mediatorConnection = MediatorLiveData<List<Connection>>().also {
it.value = connections.value
}
private val refreshLiveData = MutableLiveData(RefreshStatus.READY)
private val noMatchesEvent = SingleLiveEvent<Void>()
private val emptyTableEvent = SingleLiveEvent<Void>()
val nameLiveData = MutableLiveData<String>()
val urlLiveData = MutableLiveData<String>()
val actualStatusLiveData = MutableLiveData<String>()
init {
with(mediatorConnection) {
addSource(connections) { update() }
addSource(nameLiveData) { update() }
addSource(urlLiveData) { update() }
addSource(actualStatusLiveData) { update() }
}
}
fun getRefreshLiveData(): LiveData<RefreshStatus> = refreshLiveData
fun getNoMatchesEvent(): LiveData<Void> = noMatchesEvent
fun getEmptyTableEvent(): LiveData<Void> = emptyTableEvent
fun getConnections(): LiveData<List<Connection>> = mediatorConnection
private fun update() {
if (connections.value.isNullOrEmpty()) {
emptyTableEvent.call()
} else {
mediatorConnection.value = connections.value?.filter { connection -> getPredicate().test(connection) }
if (mediatorConnection.value.isNullOrEmpty()) {
noMatchesEvent.call()
}
}
}
update() gets triggered on screen rotation because of new subscription to mediatorConnection and MediatorLiveData.onActive() is called. And it's intented behavior
Android live data - observe always fires after config change
Code for showing toast
package com.github.aoreshin.shtatus.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.Toast
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.github.aoreshin.shtatus.R
import com.github.aoreshin.shtatus.ShatusApplication
import com.github.aoreshin.shtatus.viewmodels.ConnectionListViewModel
import javax.inject.Inject
class ConnectionListFragment : Fragment() {
#Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
private lateinit var refreshLayout: SwipeRefreshLayout
private lateinit var nameEt: EditText
private lateinit var urlEt: EditText
private lateinit var statusCodeEt: EditText
private lateinit var viewModel: ConnectionListViewModel
private lateinit var recyclerView: RecyclerView
private lateinit var viewAdapter: ConnectionListAdapter
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_connection_list, container, false)
val application = (requireActivity().application as ShatusApplication)
application.appComponent.inject(this)
val viewModelProvider = ViewModelProvider(this, viewModelFactory)
viewModel = viewModelProvider.get(ConnectionListViewModel::class.java)
bindViews(view)
setupObservers()
setupListeners()
addFilterValues()
setupRecyclerView()
return view
}
private fun setupObservers() {
with(viewModel) {
getConnections().observe(viewLifecycleOwner, Observer { viewAdapter.submitList(it) })
getRefreshLiveData().observe(viewLifecycleOwner, Observer { status ->
when (status) {
ConnectionListViewModel.RefreshStatus.LOADING -> refreshLayout.isRefreshing = true
ConnectionListViewModel.RefreshStatus.READY -> refreshLayout.isRefreshing = false
else -> throwException(status.toString())
}
})
getNoMatchesEvent().observe(viewLifecycleOwner, Observer { showToast(R.string.status_no_matches) })
getEmptyTableEvent().observe(viewLifecycleOwner, Observer { showToast(R.string.status_no_connections) })
}
}
private fun setupRecyclerView() {
viewAdapter = ConnectionListAdapter(parentFragmentManager, ConnectionItemCallback())
recyclerView.apply {
layoutManager = LinearLayoutManager(context)
adapter = viewAdapter
}
}
private fun addFilterValues() {
with(viewModel) {
nameEt.setText(nameLiveData.value)
urlEt.setText(urlLiveData.value)
statusCodeEt.setText(actualStatusLiveData.value)
}
}
private fun bindViews(view: View) {
with(view) {
recyclerView = findViewById(R.id.recycler_view)
refreshLayout = findViewById(R.id.refresher)
nameEt = findViewById(R.id.nameEt)
urlEt = findViewById(R.id.urlEt)
statusCodeEt = findViewById(R.id.statusCodeEt)
}
}
private fun setupListeners() {
with(viewModel) {
refreshLayout.setOnRefreshListener { send() }
nameEt.addTextChangedListener { nameLiveData.value = it.toString() }
urlEt.addTextChangedListener { urlLiveData.value = it.toString() }
statusCodeEt.addTextChangedListener { actualStatusLiveData.value = it.toString() }
}
}
private fun throwException(status: String) {
throw IllegalStateException(getString(R.string.error_no_such_status) + status)
}
private fun showToast(resourceId: Int) {
Toast.makeText(context, getString(resourceId), Toast.LENGTH_SHORT).show()
}
override fun onDestroyView() {
super.onDestroyView()
with(viewModel) {
getNoMatchesEvent().removeObservers(viewLifecycleOwner)
getRefreshLiveData().removeObservers(viewLifecycleOwner)
getEmptyTableEvent().removeObservers(viewLifecycleOwner)
getConnections().removeObservers(viewLifecycleOwner)
}
}
}
How I should address this issue?
After some head scratching I've decided to go with internal ViewModel statuses, this way logic in Activity/Fragment is kept to a minimum.
So now my ViewModel looks like this:
package com.github.aoreshin.shtatus.viewmodels
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.github.aoreshin.shtatus.events.SingleLiveEvent
import com.github.aoreshin.shtatus.room.Connection
import io.reactivex.FlowableSubscriber
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import io.reactivex.subscribers.DisposableSubscriber
import okhttp3.ResponseBody
import retrofit2.Response
import java.util.function.Predicate
import javax.inject.Inject
import javax.inject.Singleton
#Singleton
class ConnectionListViewModel #Inject constructor(
private val connectionRepository: ConnectionRepository
) : ViewModel() {
private var tableStatus = TableStatus.OK
private val connections = connectionRepository.allConnections()
private val mediatorConnection = MediatorLiveData<List<Connection>>()
private val stopRefreshingEvent = SingleLiveEvent<Void>()
private val noMatchesEvent = SingleLiveEvent<Void>()
private val emptyTableEvent = SingleLiveEvent<Void>()
private val nameLiveData = MutableLiveData<String>()
private val urlLiveData = MutableLiveData<String>()
private val statusLiveData = MutableLiveData<String>()
init {
with(mediatorConnection) {
addSource(connections) { update() }
addSource(nameLiveData) { update() }
addSource(urlLiveData) { update() }
addSource(statusLiveData) { update() }
}
}
fun getStopRefreshingEvent(): LiveData<Void> = stopRefreshingEvent
fun getNoMatchesEvent(): LiveData<Void> = noMatchesEvent
fun getEmptyTableEvent(): LiveData<Void> = emptyTableEvent
fun getConnections(): LiveData<List<Connection>> = mediatorConnection
fun getName(): String? = nameLiveData.value
fun getUrl(): String? = urlLiveData.value
fun getStatus(): String? = statusLiveData.value
fun setName(name: String) { nameLiveData.value = name }
fun setUrl(url: String) { urlLiveData.value = url }
fun setStatus(status: String) { statusLiveData.value = status }
private fun update() {
if (connections.value != null) {
if (connections.value.isNullOrEmpty()) {
if (tableStatus != TableStatus.EMPTY) {
emptyTableEvent.call()
tableStatus = TableStatus.EMPTY
}
} else {
mediatorConnection.value = connections.value?.filter { connection -> getPredicate().test(connection) }
if (mediatorConnection.value.isNullOrEmpty()) {
if (tableStatus != TableStatus.NO_MATCHES) {
noMatchesEvent.call()
tableStatus = TableStatus.NO_MATCHES
}
} else {
tableStatus = TableStatus.OK
}
}
}
}
fun send() {
if (!connections.value.isNullOrEmpty()) {
val singles = connections.value?.map { connection ->
val id = connection.id
val description = connection.description
val url = connection.url
var message = ""
connectionRepository.sendRequest(url)
.doOnSuccess { message = it.code().toString() }
.doOnError { message = it.message!! }
.doFinally {
val result = Connection(id, description, url, message)
connectionRepository.insert(result)
}
}
Single.mergeDelayError(singles)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doFinally { stopRefreshingEvent.call() }
.subscribe(getSubscriber())
} else {
stopRefreshingEvent.call()
}
}
private fun getSubscriber() : FlowableSubscriber<Response<ResponseBody>> {
return object: DisposableSubscriber<Response<ResponseBody>>() {
override fun onComplete() { Log.d(TAG, "All requests sent") }
override fun onNext(t: Response<ResponseBody>?) { Log.d(TAG, "Request is done") }
override fun onError(t: Throwable?) { Log.d(TAG, t!!.message!!) }
}
}
private fun getPredicate(): Predicate<Connection> {
return Predicate { connection ->
connection.description.contains(nameLiveData.value.toString(), ignoreCase = true)
&& connection.url.contains(urlLiveData.value.toString(), ignoreCase = true)
&& connection.actualStatusCode.contains(
statusLiveData.value.toString(),
ignoreCase = true
)
}
}
private enum class TableStatus {
NO_MATCHES,
EMPTY,
OK
}
companion object {
private const val TAG = "ConnectionListViewModel"
}
}
And corresponding Fragment looks like this:
package com.github.aoreshin.shtatus.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.Toast
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.github.aoreshin.shtatus.R
import com.github.aoreshin.shtatus.ShatusApplication
import com.github.aoreshin.shtatus.viewmodels.ConnectionListViewModel
import javax.inject.Inject
class ConnectionListFragment : Fragment() {
#Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
private lateinit var refreshLayout: SwipeRefreshLayout
private lateinit var nameEt: EditText
private lateinit var urlEt: EditText
private lateinit var statusCodeEt: EditText
private lateinit var viewModel: ConnectionListViewModel
private lateinit var recyclerView: RecyclerView
private lateinit var viewAdapter: ConnectionListAdapter
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_connection_list, container, false)
val application = (requireActivity().application as ShatusApplication)
application.appComponent.inject(this)
val viewModelProvider = ViewModelProvider(this, viewModelFactory)
viewModel = viewModelProvider.get(ConnectionListViewModel::class.java)
bindViews(view)
setupObservers()
setupListeners()
addFilterValues()
setupRecyclerView()
return view
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
if (savedInstanceState != null) {
refreshLayout.isRefreshing = savedInstanceState.getBoolean(REFRESHING, false)
}
}
private fun setupObservers() {
with(viewModel) {
getConnections().observe(viewLifecycleOwner, Observer { viewAdapter.submitList(it) })
getStopRefreshingEvent().observe(viewLifecycleOwner, Observer { refreshLayout.isRefreshing = false })
getNoMatchesEvent().observe(viewLifecycleOwner, Observer { showToast(R.string.status_no_matches) })
getEmptyTableEvent().observe(viewLifecycleOwner, Observer { showToast(R.string.status_no_connections) })
}
}
private fun setupRecyclerView() {
viewAdapter = ConnectionListAdapter(parentFragmentManager, ConnectionItemCallback())
recyclerView.apply {
layoutManager = LinearLayoutManager(context)
adapter = viewAdapter
}
}
private fun addFilterValues() {
with(viewModel) {
nameEt.setText(getName())
urlEt.setText(getUrl())
statusCodeEt.setText(getStatus())
}
}
private fun bindViews(view: View) {
with(view) {
recyclerView = findViewById(R.id.recycler_view)
refreshLayout = findViewById(R.id.refresher)
nameEt = findViewById(R.id.nameEt)
urlEt = findViewById(R.id.urlEt)
statusCodeEt = findViewById(R.id.statusCodeEt)
}
}
private fun setupListeners() {
with(viewModel) {
refreshLayout.setOnRefreshListener { send() }
nameEt.addTextChangedListener { setName(it.toString()) }
urlEt.addTextChangedListener { setUrl(it.toString()) }
statusCodeEt.addTextChangedListener { setStatus(it.toString()) }
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putBoolean(REFRESHING, refreshLayout.isRefreshing)
}
private fun showToast(resourceId: Int) {
Toast.makeText(context, getString(resourceId), Toast.LENGTH_SHORT).show()
}
override fun onDestroyView() {
super.onDestroyView()
with(viewModel) {
getNoMatchesEvent().removeObservers(viewLifecycleOwner)
getEmptyTableEvent().removeObservers(viewLifecycleOwner)
getStopRefreshingEvent().removeObservers(viewLifecycleOwner)
getConnections().removeObservers(viewLifecycleOwner)
}
}
companion object {
private const val REFRESHING = "isRefreshing"
}
}
Pros
No additional dependencies
Usage of widespread SingleLiveEvent
Pretty straightforward to implement
Cons
Conditional logic is quickly getting out of hand even in this simple case, surely needs refactoring. Not sure if this approach will work in real-life complex scenarios.
If there are cleaner and more concise approaches to solve this problem I will be happy to hear about them!
In your solution; you introduced TableStatus which is acting like flag and not needed.
If you really looking for a good Android Architecture; instead you could just do
if (viewLifecycleOwner.lifecycle.currentState == Lifecycle.State.RESUMED) {
showToast(R.string.status_no_connections)
and
if (viewLifecycleOwner.lifecycle.currentState == Lifecycle.State.RESUMED) {
showToast(R.string.status_no_matches)
NOTE:
viewLifecycleOwner.lifecycle.currentState == Lifecycle.State.RESUMED
is not a patch Google implemented this fix in support library as well.
And remove #Singleton from (why would you need it to be singleton)
#Singleton
class ConnectionListViewModel #Inject constructor(
PS:
From the top of my head looks like; you may also don't need SingleLiveEvent for you case.
(would love to talk more on this if you want I also just have started Kotlin + Clear & Scalable Android Architecture)

Categories

Resources