How to communicate between Fragments and Activities

While I am browsing other existing projects in Android community I can see few worrying problems. Today I would like to pay attention to proper way in communication between Fragments and Activities.

Generally the biggest problem appears when we have to pass information from Fragment to his Activity. I would like to start with the showing of the most frequent mistake. Many developers do something like this:

It is really bad because we addict our Fragment to specific Activity and we can’t reuse it. Moreover Android documentation says:

You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a “sub activity” that you can reuse in different activities).

One of the most important principles of clean code are: Do not repeat yourself, which means we should create modular and reusable code, but the above example breaks this principle, because probably in future we will have to create different Fragment when we will use it with another Activity.

Furthermore when we will try to use this code in different Activity, app will crash only when we press the button. It causes possibility to skip the mistake, so a good solution is, to inform as soon as possible about wrong implementation.

How can we make it right?

First don’t addict your Fragment to specific Activity, instead of this use interface:

Second improvement is to get listener while Fragment is attaching to his parent. It brings us some benefits. When we forget about implementing interface in our Activity, application will crash during creating Fragment. It is fast fail strategy which is very good solution in this case.

What if you want to communicate with parent Fragment?
Well, I have prepared library in Java and Kotlin for you:

FragmentUtils library

In one function it provides communication with parent Fragment or Activity.

See the implementation:

1. Kotlin version of library with extension function for Fragments

2. Java version of library

3. Fast fail strategy is included in library as well:

Note: It uses, because has been deprecated since Android P

If you find out something useful from this article, give me 👏🏼 and star on Github project.

Senior Android Developer @ Espeo Software. Kotlin lover. Tech stack: MVVM, Dagger2, Coroutines, RxJava2, Android Architecture Components

The (retired) Pub(lication) for Android & Tech, focused on Development