-1

I want to send data from fragment to fragment using arguments the way I am doing is mentioned below.

here's on button click data sent to fragment using argument

//sender fragment 
view.btnjavafragment.setOnClickListener {
            newInstance("helllo")
        }

  companion object {
        @JvmStatic
        fun newInstance(mystring:String) = javaFragment().apply {
            arguments = Bundle().apply {
              putString("sentdata",mystring)
              if(arguments!=null){
                  Toast.makeText(context,"data sent",Toast.LENGTH_SHORT).show()
              }
            }
        }
    }

//receiving fragment 
override fun onAttach(context: Context?) {
        super.onAttach(context)
        arguments?.getString("sentdata","")?.let {
            string = it
            tvdatamessage.setText(string)
        }
    }

Ramesh R
  • 7,009
  • 4
  • 25
  • 38
Black mamba
  • 462
  • 4
  • 15
  • Possible duplicate of [How to send data from one Fragment to another Fragment?](https://stackoverflow.com/questions/24555417/how-to-send-data-from-one-fragment-to-another-fragment) – Wale Jul 02 '19 at 10:42

3 Answers3

2

Hi Please follow below link for your solutions.

https://www.journaldev.com/14207/android-passing-data-between-fragments

You can also use Navigation Graph for Fragment Transaction and directly send any kind of data in bundle to send it like below.

var nameBundle = Bundle()
nameBundle.putString("youKey", edtName.text.toString())
it.findNavController().navigate(R.id.tofragmentName, nameBundle)
Jyubin Patel
  • 1,373
  • 7
  • 17
-1

It is not recommended that two Fragments should communicate directly. Check out the documentation and examples here. https://developer.android.com/training/basics/fragments/communicating

I would recommend a common ViewModel and observe the changes there.

KunBa
  • 235
  • 5
  • 12
-1

You can use SafeArgs that are part of Navigation component on Jetpack. Here you have nice tutorial made by Google.

solaza
  • 1,251
  • 1
  • 17
  • 30