Andrew
Andrew

Reputation: 2157

Why I can't receive data from DialogFragment to Fragment?

I'm trying to send data from DialogFragment to Fragment from which this dialog was created. At target fragment I use this code:

val noteData = NoteData()
val bundle = Bundle()
noteData.setTargetFragment(this,0)
noteData.show(fragmentManager!!, noteData.TAG)

and I also implemented my interface at fragment:

class NotepadScr : Fragment(), NotesInterface

At DialogFragment I use this code:

private var notesInterface: NotesInterface? = null
 override fun onAttach(context: Context) {
        super.onAttach(context)

        if (context is NotesInterface) {
            notesInterface = context
        } else if (parentFragment is NotesInterface) {
            notesInterface = parentFragment as NotesInterface
        }
    }

and send data:

notesInterface.archiveNote(recordID!!)

I also tried to use onActivityResult() from this question:

val i = Intent()
i.putExtra("selectedDate", 1122)
targetFragment!!.onActivityResult(1, Activity.RESULT_OK, i)

receiving data:

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        when(requestCode){
            1->{
                if (resultCode == Activity.RESULT_OK) {
                    // here the part where I get my selected date from the saved variable in the intent and the displaying it.
                    val bundle = data!!.extras
                    val resultDate = bundle!!.getInt("selectedDate")
                    Timber.i("****************************   %s", resultDate.toString())
                }
            }
        }
    }

but I didn't manage to receive data :(((

Upvotes: 0

Views: 58

Answers (1)

keshav kowshik
keshav kowshik

Reputation: 2374

Data has to be sent as shown below:

ReceivingFragment receivingFragment = new ReceivingFragment
Bundle bundle = new Bundle()
bundle.putString(KEY, value to be sent);//Use Int if you want to send int value
receivingFragment.setArguments(bundle);

This has to be done in receiving fragment

String receivingData = getArguments.getString(KEY);

Make sure KEY is same in both sending fragment and receiving fragment.

Upvotes: 1

Related Questions