how can I implement LiveData Observer in the Recycler View? I have a global var `someDataChanged' that gets updated from another Fragment. Any help would be greatly appreciated!
class GlobalActivity {
companion object {
someDataChanged = MutableLiveData<Int>()
}
}
Then in the Adapter.kt for the RecyclerView I need to listen if the someDataChanged. I have the following code:
Adapter.kt
var mRecyclerView: RecyclerView? = null
class MainAdapter(val myResponse: MyResponse): RecyclerView.Adapter<CustomViewHolder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomViewHolder {
//Error: this is not recognized.
GlobalActivity.someDataChanged`.observe(this, Observer{
println("Data Changed")
})
val layoutInflater = LayoutInflater.from(parent?.context)
val cellForRow = layoutInflater.inflate(R.layout.my_custom_cell, parent,false)
return CustomViewHolder(cellForRow)
}
override fun onBindViewHolder(holder: CustomViewHolder, position: Int) {
//some code
class CustomViewHolder(val view: View, var myPass: Passes? = null): RecyclerView.ViewHolder(view){
}
}
}
Not sure if I understood your question but if you want to update your recycler view every time the liveData is updated you should create something like this:
class MyActivity : AppCompatActivity() {
private val viewModel: MyViewModel by viewModels()
lateinit var adapter: MyAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
adapter = MyAdapter()
recyclerView.adapter = adapter
viewModel.myLiveData.observe(this, Observer { newContent ->
adapter.updateContent(newContent)
})
}
}
class MyViewModel: ViewModel() {
private val _myLiveData = MutableLiveData<String>()
val myLiveData: LiveData<String> = _myLiveData
// You should call this to update you liveData
fun updateInfo(newInfo: String) {
_myLiveData.value = newInfo
}
}
class MyAdapter: RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private var content: String = ""
...
fun updateInfo(newString: String) {
content = newString
notifyDataSetChanged() //or you can implement a DiffUtil.Callback
}
}
in RecyclerView.Adapter need to override onCreateViewHolder, pass lifeCycleOwner
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
val lifeCycleOwner = parent.context as LifecycleOwner
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_layout, parent, false)
return ItemViewHolder(view, lifeCycleOwner)
}
your inner class constructor, should have lifecycleOwner as param
inner class ItemViewHolder(view: View, private val lifecycleOwner: LifecycleOwner) : RecyclerView.ViewHolder(view) {
then you can use code as normally
mutableLiveData.observe(lifecycleOwner) { /** your logic handle **/ }
Related
Id like to initially have a list show up on my recyclerView before implementing some kind of edit function to it. However, no matter what I do, the list I made wont show up. I've got a feeling that I'm doing something wrong with the bind function.
Here is my adapter
class WorkoutAdaptor (
var workouts: List<Workout>
) : RecyclerView.Adapter<WorkoutAdaptor.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val workoutCardBinding = WorkoutCardBinding.inflate(
LayoutInflater.from(parent.context), parent, false)
return ViewHolder(workoutCardBinding)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(workouts[position])
}
override fun getItemCount(): Int {
return workouts.size
}
inner class ViewHolder(private val workoutCardBinding: WorkoutCardBinding) :
RecyclerView.ViewHolder(workoutCardBinding.root) {
fun bind(workout: Workout) {
workoutCardBinding.apply {
tvWorkoutCard
}
}
}
}
and here is my main activity
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.btnNext.setOnClickListener {
Intent(this, SecondActivity::class.java).also {
startActivity(it)
}
}
// var workout = intent.getSerializableExtra("EXTRA_WORKOUT")
// binding.tvWorkoutCard.text = workout.toString()
var workoutList = mutableListOf(
Workout("a","d","d","d"),
Workout("a","d","d","d"),
Workout("a","d","d","d"),
Workout("a","d","d","d"),
Workout("a","d","d","d"),
)
val adaptor = WorkoutAdaptor(workoutList)
binding.recyclerView.adapter = adaptor
binding.recyclerView.layoutManager = LinearLayoutManager(this)
}
}
Change your bind method to this.
fun bind(workout: Workout) {
workoutCardBinding.textview.text = workout.objectName
}
So I was able to get to a close point in creating the MultiView ViewHolder, but I am still a bit confused with some details. First how would I fill in the RecyclerView since I have multiple data classes(in this case, manually). Second, how would the Adapter know when to show a particular view? I'll leave the code here
Data Class(es)
sealed class InfoRecyclerViewItems{
class WithPicture (
val id: Int,
val movieName: String,
val thoughts: String
): InfoRecyclerViewItems()
class WithoutPicture(
val id: Int,
val movieName: String,
val thoughts: String
): InfoRecyclerViewItems()
}
The Adapter
class RecyclerViewAdapter(infoItems: MutableList<InfoRecyclerViewItems>): RecyclerView.Adapter<MainViewHolder>() {
private var infoItems1: MutableList<InfoRecyclerViewItems>
init {
this.infoItems1 = infoItems
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainViewHolder {
return when(viewType){
R.layout.container_one -> MainViewHolder.WithPictureViewHolder(
ContainerOneBinding.inflate(
LayoutInflater.from(parent.context), parent, false)
)
R.layout.container_two -> MainViewHolder.WithoutPictureViewHolder(
ContainerTwoBinding.inflate(
LayoutInflater.from(parent.context), parent, false)
)
else -> throw IllegalArgumentException("Invalid view given")
}
}
override fun onBindViewHolder(holder: MainViewHolder, position: Int) {
when(holder){
is MainViewHolder.WithPictureViewHolder -> holder.bind(infoItems1[position] as InfoRecyclerViewItems.WithPicture)
is MainViewHolder.WithoutPictureViewHolder -> holder.bind(infoItems1[position] as InfoRecyclerViewItems.WithoutPicture)
}
}
override fun getItemCount() = infoItems1.size
override fun getItemViewType(position: Int): Int {
return when(infoItems1[position]){
is InfoRecyclerViewItems.WithPicture -> R.layout.container_one
is InfoRecyclerViewItems.WithoutPicture -> R.layout.container_two
}
}
}
The ViewHolder(s)
sealed class MainViewHolder(binding: ViewBinding) : RecyclerView.ViewHolder(binding.root) {
class WithPictureViewHolder(private val binding: ContainerOneBinding) : MainViewHolder(binding){
fun bind(items: InfoRecyclerViewItems.WithPicture){
binding.part1 = items
binding.executePendingBindings()
}
}
class WithoutPictureViewHolder(private val binding: ContainerTwoBinding) : MainViewHolder(binding){
fun bind(items: InfoRecyclerViewItems.WithoutPicture){
binding.part2 = items
binding.executePendingBindings()
}
}
}
Main Activity
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.recyclerView.apply {
setHasFixedSize(true)
layoutManager = LinearLayoutManager(this#MainActivity)
}
}
}
Any suggestions are welcomed, Thank You.
SO I figured it out. based on this setup, I can create an empty MutableList and then call each different data class that I want to fill in. those data classes are linked to the ViewHolder that it is associated to, thus creating two different views inside the RecylerView.
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var manager: LinearLayoutManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val information: MutableList<InfoRecyclerViewItems> = ArrayList()
information.add(InfoRecyclerViewItems.WithPicture(2, "The Fallen", "ok"))
information.add(InfoRecyclerViewItems.WithoutPicture(4, "Black Panther", "10/10, Fantastic Movie"))
manager = LinearLayoutManager(this)
binding.recyclerView.apply {
adapter = RecyclerViewAdapter(information)
layoutManager = manager
}
}
}
Then you can just keep adding to whatever view you chose to add it to
P.S. The other files(ViewHolder, Adapter and Data Class) stay the same.
i am stuck in the problem that, i want to visit my ViewModel in a RecyclerView´s Adapter, but i have the Exception:
"Your activity is not yet attached to the Application instance. You can't request ViewModel before onCreate call"
class FoodInSortAdapter( val activity:MainActivity,private val list:List<String>):RecyclerView.Adapter<FoodInSortAdapter.Holder>() {
val viewModel :FoodViewModel by lazy {
println("servus")
ViewModelProvider(activity).get(FoodViewModel::class.java)}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.sortitem, parent, false)
return Holder(view)
}
override fun onBindViewHolder(holder: Holder, position: Int) {
holder.sortName.text = list[position]
holder.itemView.setOnClickListener {
val m=list[position]
viewModel.setQuery(m)
}
}
anyone know what ´s wrong?
thanks
First things first, you should not initialize viewModel outside of activity or fragment.
I assume you do not create adapter in onCreate but during initialization phase. There are two solution for your concern.
Initialize vm in activity, and set it in adapter by newly added method setupViewModel, called in onCreate. That's the better one.
class FooActivity : Activity{
private val viewModel: FoodViewModel by lazy {
println("servus")
ViewModelProvider(activity).get(FoodViewModel::class.java)
}
private val adapter = FoodInSortAdapter(emptyList())
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
adapter.setupViewModel(viewModel)
}
}
class FoodInSortAdapter(private val list:List<String>):RecyclerView.Adapter<FoodInSortAdapter.Holder>() {
private lateinit var viewModel: FoodViewModel
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.sortitem, parent, false)
return Holder(view)
}
override fun onBindViewHolder(holder: Holder, position: Int) {
holder.sortName.text = list[position]
holder.itemView.setOnClickListener {
val m=list[position]
viewModel.setQuery(m)
}
}
fun setupViewModel(vm: FoodViewModel){
viewModel = vm
}
}
Create adapter in onCreate method, that should also work for you.
Cheers
I have a RecyclerView displaying data from a Dao.
In the data that is shown in the recyclerView is a button with which the item should get deleted.
I know the function for that is :
fun deleteReceipt(receipts: Receipts) = viewModelScope.launch {
receiptDao.delete(receipts)
}
But I am not quite sure where to put it and call it. Because if I want to call it in the Adapter where i set the other displayed Item values I have no access to the Dao
Here is the fragment:
#AndroidEntryPoint
class HistoryFragment : Fragment(R.layout.fragment_history) {
private val viewModel: PurchaseViewmodel by viewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val binding = FragmentHistoryBinding.bind(view)
val exampleAdapter = ExampleAdapter()
binding.apply{
recyclerView.apply{
layoutManager = LinearLayoutManager(requireContext())
adapter = exampleAdapter
setHasFixedSize(true)
}
}
setFragmentResultListener("add_receipt_request"){_,bundle ->
val result = bundle.getInt("add_receipt_request")
viewModel.onAddResult(result)
}
viewModel.receipts.observe(viewLifecycleOwner){ /// New Items get passed to the List
exampleAdapter.submitList(it)
}
}
}
The ViewModel:
#HiltViewModel
class PurchaseViewmodel #Inject constructor(
private val receiptDao: ReceiptDao
): ViewModel() {
private val tasksEventChannel = Channel<TasksEvent>()
val addTaskEvent = tasksEventChannel.receiveAsFlow()
val receipts = receiptDao.getAllReceipts().asLiveData()
fun onAddResult(result: Int){
when (result){
ADD_RECEIPT_RESULT_OK ->showReceiptSavedConfirmation("Receipt is saved")
}
}
private fun showReceiptSavedConfirmation (text: String) = viewModelScope.launch {
tasksEventChannel.send(TasksEvent.ShowReceiptSavedConfirmation(text))
}
fun deleteReceipt(receipts: Receipts) = viewModelScope.launch {
receiptDao.delete(receipts)
}
sealed class TasksEvent {
data class ShowReceiptSavedConfirmation(val msg: String) : TasksEvent()
}
}
And the Adapter:
class ExampleAdapter : ListAdapter<Receipts,ExampleAdapter.ExampleViewHolder>(DiffCallback()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ExampleViewHolder { // Basically how to get a new Item from the List and display it
val binding = ReceiptsBinding.inflate(LayoutInflater.from(parent.context),parent,false)
return ExampleViewHolder(binding)
}
override fun onBindViewHolder(holder: ExampleViewHolder, position: Int) {
val currentItem = getItem(position)
holder.bind(currentItem)
}
override fun getItemCount(): Int {
return super.getItemCount()
}
class ExampleViewHolder(private val binding: ReceiptsBinding) : RecyclerView.ViewHolder(binding.root){ //Examples One Row in our list
fun bind (receipts: Receipts) {
binding.apply {
storeHistory.text = receipts.store
amountHistory.text = receipts.total
dateHistory.text = receipts.date
}
}
}
class DiffCallback : DiffUtil.ItemCallback<Receipts>() {
override fun areItemsTheSame(oldItem: Receipts, newItem: Receipts) =
oldItem.id == newItem.id
override fun areContentsTheSame(oldItem: Receipts, newItem: Receipts) =
oldItem == newItem
}
}
Create a listener using Interface
Implement the listener in Fragment
Create listener variable in Adapter
pass the listener from fragment to adapter
pass the listener to viewHolder
on Delete button click of that item call the listener method, which will trigger the implementation in Fragment where you have access to your ViewModel
delete the receipt using viewModel.deleteReceipt
I know that there are similar questions to this, but I just cant find something that is similar, I've been studying new things to learn, and while converting kotlin synthetics to viewvbinding mode, I've encountered this error
kotlin.UninitializedPropertyAccessException: lateinit property binding has not been initialized
at com.codepalace.chatbot.ui.MessagingAdapter.onBindViewHolder(MessagingAdapter.kt:60)
at com.codepalace.chatbot.ui.MessagingAdapter.onBindViewHolder(MessagingAdapter.kt:17)
It says that I have to initialize the binding, but I dont know where to put it.
This is the code.
class MessagingAdapter: RecyclerView.Adapter<MessagingAdapter.MessageViewHolder>() {
var messagesList = mutableListOf<Message>()
private lateinit var binding: MessageItemBinding
inner class MessageViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
init {
itemView.setOnClickListener {
//Remove message on the item clicked
messagesList.removeAt(adapterPosition)
notifyItemRemoved(adapterPosition)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MessageViewHolder {
return MessageViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.message_item, parent, false)
)
}
override fun getItemCount(): Int {
return messagesList.size
}
#SuppressLint("SetTextI18n")
override fun onBindViewHolder(holder: MessageViewHolder, position: Int) {
val currentMessage = messagesList[position]
when (currentMessage.id) {
SEND_ID -> {
holder.itemView.findViewById<View>(R.id.tv_message).apply {
binding.tvMessage.text = currentMessage.message
visibility = View.VISIBLE
}
holder.itemView.findViewById<View>(R.id.tv_bot_message).visibility = View.GONE
}
RECEIVE_ID -> {
holder.itemView.findViewById<View>(R.id.tv_bot_message).apply {
binding.tvBotMessage.text = currentMessage.message
visibility = View.VISIBLE
}
holder.itemView.findViewById<View>(R.id.tv_message).visibility = View.GONE
}
}
}
fun insertMessage(message: Message) {
this.messagesList.add(message)
notifyItemInserted(messagesList.size)
}
private lateinit var binding: MessageItemBinding
You didn't initialize the binding object, as you defined it as lateinit, then you should define it.
This is typically in onCreateViewHolder
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TrackedActivityHolder {
val inflater = LayoutInflater.from(parent.context)
binding = DataBindingUtil.inflate<MessageItemBinding>(inflater, R.layout.message_item, parent, false)
return MessageViewHolder(
binding
)
}
UPDATE
You need to accept MessageItemBinding type instead of View in the MessageViewHolder constructor, and use itemView.root to get the root view of the list item.
inner class MessageViewHolder(itemView: MessageItemBinding) : RecyclerView.ViewHolder(itemView.root) {
init {
itemView.root.setOnClickListener {
//Remove message on the item clicked
messagesList.removeAt(adapterPosition)
notifyItemRemoved(adapterPosition)
}
}
}
The reason why You get this error is that MessageItemBinding should not be in Adapter but in ViewHolder class. You can make RecyclerView like this:
object MessageDiffCallback : DiffUtil.ItemCallback<Message>()
{
override fun areItemsTheSame(
oldItem: Message,
newItem: Message
): Boolean =
oldItem.id == newItem.id
override fun areContentsTheSame(
oldItem: Message,
newItem: Message
): Boolean =
oldItem == newItem
}
I assume that Message is a data class. You have to create this MessageDiffCallback and override these 2 methods in a similar way that I did it.
Now Create ViewHolder class:
class MessageViewHolder private constructor(
private val binding: MessageItemBinding
) : RecyclerView.ViewHolder(binding.root)
{
companion object
{
fun create(parent: ViewGroup): MessageViewHolder
{
val layoutInflater = LayoutInflater.from(parent.context)
val binding = MessageItemBinding.inflate(layoutInflater, parent, false)
return MessageViewHolder(
binding
)
}
}
fun bind(
message: Messaage
)
{
// Here You can do everything.
// You pass the message and based on this You can set up a view and use binding
}
}
And now Adapter class
class MessageAdapter : ListAdapter<Message, MessageViewHolder>(MessageDiffCallback)
{
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MessageViewHolder =
MessageViewHolder.create(parent)
override fun onBindViewHolder(holder: MessageViewHolder, position: Int) =
holder.bind(
message = getItem(position),
)
}
Now You should have a working adapter. To put data in it use messageAdapter.submitList(messages) in Your Fragment/Activity
Maybe not the best answer because it changes Your code and uses a little different logic but it should work better. You can check google sample code here or take codelab here. It is free after signing up