Passing data between a fragment and its container activity

Try using interfaces.

Any fragment that should pass data back to its containing activity should declare an interface to handle and pass the data. Then make sure your containing activity implements those interfaces. For example:

JAVA

In your fragment, declare the interface…

public interface OnDataPass {
    public void onDataPass(String data);
}

Then, connect the containing class’ implementation of the interface to the fragment in the onAttach method, like so:

OnDataPass dataPasser;

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    dataPasser = (OnDataPass) context;
}

Within your fragment, when you need to handle the passing of data, just call it on the dataPasser object:

public void passData(String data) {
    dataPasser.onDataPass(data);
}

Finally, in your containing activity which implements OnDataPass

@Override
public void onDataPass(String data) {
    Log.d("LOG","hello " + data);
}

KOTLIN

Step 1. Create Interface

interface OnDataPass {
    fun onDataPass(data: String)
}

Step 2. Then, connect the containing class’ implementation of the interface to the fragment in the onAttach method (YourFragment), like so:

lateinit var dataPasser: OnDataPass

override fun onAttach(context: Context) {
    super.onAttach(context)
    dataPasser = context as OnDataPass
}

Step 3. Within your fragment, when you need to handle the passing of data, just call it on the dataPasser object:

fun passData(data: String){
    dataPasser.onDataPass(data)
}

Step 4. Finally, in your activity implements OnDataPass

class MyActivity : AppCompatActivity(), OnDataPass {}

override fun onDataPass(data: String) {
    Log.d("LOG","hello " + data)
}

Leave a Comment