I am trying to make a DialogFragment which can be reused in different Fragments without creating a new one using the following code.
All this code that I am going to put below works correctly, the buttons work, the texts are also seen, the problem is when I press the Recent Applications button of the mobile, the app crashes with the following error:
android.os.BadParcelableException: Parcelable encountered IOException writing serializable object(name = com.mypackage.models.MyDialogInfo)
I am creating a DialogFragment called MyCustomDialogFragment which receives MyDialogInfo model as an argument.
class MyDialogInfo(
val id:String,
val title:String,
val body:String,
val firstButton: ButtonInfo?=null,
val secondaryButton: ButtonInfo?= null
):Serializable
class ButtonInfo(
val text:String?=null,
val textCharSequence:CharSequence?=null,
val callback: CallbackButton
):Serializable{
interface CallbackButton{
fun onAction()
}
}
In MyCustomDialogFragment I'm receiving arguments and using them like this:
private val args: MyCustomDialogFragmentArgs by navArgs()
override fun onViewCreated(view:View, savedInstanceState:Bundle?){
super.onViewCreated(view,savedInstanceState)
setUpPrimaryButton(args.dialoginfo.firstButton)
setUpSecondaryButton(args.dialoginfo.secondaryButton)
}
private fun setUpPrimaryButton(button: ButtonInfo?){
with(binding){
if(button == null){
btPrimary.hide()
}else {
btPrimary.show()
btPrimary.text= button.text
btPrimary.setOnClickListener{
dismiss()
args.dialoginfo.firstButton?.callback?.onAction()
}
}
}
}
private fun setUpSecondaryButton(button: ButtonInfo?){
with(binding){
if(button == null){
btSec.hide()
}else {
btSec.show()
if(!button.text.isNullOrEmpty()){
btSec.text = button.text
}else if(!button.textChar.isNullOrEmpty()){
btSec.text = button.textChar
}
btSec.setOnClickListener{
dismiss()
args.dialoginfo.secondaryButton?.callback?.onAction()
}
}
}
}
Then, in other Fragments, I use this DialogFragment in this way:
private var customDialogInfo :MyDialogInfo?=null
override fun onViewCreated(view:View, savedInstanceState:Bundle?){
super.onViewCreated(view,savedInstanceState)
setUpButton()
}
private setUpButton(){
btnDoSomething.setOnClickListener{
goToCustomDialog(
title = "Title",
body = "Body",
fistButton = ButtonInfo(
text = "Text Button",
callback = object: CallbackButton{
override fun onAction(){
//Do Something
}
}
),
secondaryButton = ButtonInfo(
text = "Text Button 2",
callback = object: CallbackButton{
override fun onAction(){
//Do Something
}
}
)
)
}
}
private fun goToCustomDialog(
title:String,
body:String,
firstButton: ButtonInfo?=null,
secondaryButton: ButtonInfo?= null
){
customDialogInfo = MyDialogInfo(
id= UUID.randomUUID().toString(),
title = title,
body = body,
firstButton = firstButton,
secondaryButton = secondaryButton
)
findNavController().navigate(R.id.custom_dialog_fragment, bundleOf(Pair("dialoginfo",customDialogInfo)))
}