Constructor of a Fragment in Android

Recently, I came to a very strange issue in Android development and I wish to share a very important lesson. As an Android developer, you might be knowing that most of the crashes are related to lifecycle events of Activities and Fragments. Moreover, most phone manufacturers patch the original Android system to come up with their own versions. Such versions might have a hostile kernel which may kill Activities more frequently to claim more free space and faster performance for foreground apps. This makes Android development difficult as you have to check for each of the edge cases that may occur.

One of the best ways to debug such crashes is to use the "Don't Keep Activities" feature of the development mode. This kills the Activities and the fragments as soon as the app goes to the background. Enable this mode and start your app and navigate through all your Activities and Fragments. If you get no faulty behaviour, then your app is of quality-at-par.

Let's take a closer look at how Android resumes a stopped Activity. The Android system has something called Intent which is passed to each Activity when it is created. This Intent contains the necessary information that can be used to construct the Activity and is the only determinant for stateless Activities. When an Activity goes to the background, the Activity might be destroyed, but the Intent is saved. When the Activity resumes, it gets back its Intent to resume itself.

What about Fragments though? As soon as an Activity resumes, the Fragment Manager resumes all its associated Fragments as well. However, Fragments have to such thing as Intent. When Fragment Manager re-creates a Fragment, it has no way of passing any parameters to it. In such a case, the Fragment Manager always looks for a public constructor taking no parameters and if it is unable to find it, the app will crash throwing an exception.

Takeaway: Always create a public constructor with no parameter for a Fragment.

By default, Android creates a public constructor with no parameter, so it is also okay to have no constructor at all. The question remains: How do I pass arguments to Fragments at all? Well, the best way to do it is to create a static method the creates new instances of the Fragment. In that static method, one needs to create a Bundle and use setArguments() method to set the bundle as the argument. Now, whenever the Fragment resumes, it will automatically receive the bundle in its onCreate(). Here is a sample for the same.


Popular posts from this blog

DDoS Attack on Bitotsav '19 Website

Popular ethical hacking tricks on LAN

Rendering Performance Evaluation - Android SDK vs React Native