Context: No receiver is declared in the manifest since I am not declaring a new receiver.
I am a bit confused about why the receiver in MainActivity does not receieve the broadcast sent from the recycler adapter.
RecyclerAdapter
holder.checkBox.setOnClickListener {view ->
item.completed = holder.checkBox.isChecked
Log.i("wow", "is checked: ${holder.checkBox.isChecked}")
val intent = Intent().apply {
addCategory(Intent.CATEGORY_DEFAULT)
setAction(changeCompletedForDeck)
putExtra(changeCompletedForDeckItemID, item)
}
LocalBroadcastManager.getInstance(view.context).sendBroadcast(intent)
MainActivity
private lateinit var broadcastReceiver: BroadcastReceiver
broadcastReceiver = object: BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
//get deck, if deck != null then update the checkmark response
if (intent?.action == DeckRecyclerAdapter.changeCompletedForDeck) {
val deck = intent?.extras?.getParcelable<Deck>(DeckRecyclerAdapter.changeCompletedForDeckItemID)
Log.i("wow", "${deck?.title}")
deck?.let { deck ->
globalViewModel.update(deck)
}
}
}
}
val filter = IntentFilter(DeckRecyclerAdapter.changeCompletedForDeck)
LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, filter)
//Destroy the BroadcastReceiver
override fun onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver)
super.onDestroy()
}
Your problem is
Intentaction . See at the time of register you have not provided any action so receiver will not be identified by the system. You can define a specific action withIntentFilterand use the same action during register andsendBroadcast.To identify different conditions you can do two things.
Bundleand validate the bundle value insideonReceive()IntentFilterand validate the action insideonReceive()See this.So with the first way have a constant action in
MainActivity:-Then for sending broadcast use the code below
addCategory(Intent.CATEGORY_DEFAULT)is not required:-PS- However i don't think you should be using a
Broadcastreceiverjust to provide a callback fromAdapterits purpose is more than that. You should be using a callback listener for it . SinceRecyclerView.Adapterwill binds to a UI component a callback interface will be fine . I think abroadcastReceiveris overkill in this usecase .