Loading...
Home
  • Tech Blogs
  • Videos
  • Conferences
    • Droidcon News
    • Upcoming Conferences
    • Become a Partner
    • Past Events
    • Keep Me Informed
    • Diversity Scholarships
  • Community
    • droidcon Team
    • How to Hold a Droidcon
  • Android Careers
Sign In

Global CSS

 

Fragment and constructor dependencies

 

 
Jobin Lawrance
Senior Software Engineer @ Dealersocket, Recro
Published: November 19, 2020
Tweet
Share
 

Image by Jibin Lawrance

 

Anyone working on Android development for a while would have come across this crash if they’ve written any fragment code

 

 

Image for post
 

This happens when Android’s FragmentManager is unable to instantiate the current fragment as it couldn’t find an empty fragment constructor.

Well, how does one end up here?

 

 

For the most part, we can have a code like this and get away with a functioning application that is unless our app goes through a process-death or configuration change and Android starts recreating everything.

 

Looking at the fixes

There are two ways to go about addressing this issue and let’s look at each of them.

 

1. Fragment Factory

Here we create a FragmentFactory with the same arguments that we passed to the fragment’s constructor and delegate the responsibility of instantiating the fragment to the factory.

We then assign this factory to the parent activity’s (or fragment) fragmentManager in theonCreate function before super.onCreate(..) call.

Now the FragmentManager uses this factory to recreate our fragment whenever necessary.

Our above code will look like this

 

 

We can further tidy things up a bit by creating a lazy extension function.

 

 

Now we can change lateinit var mainFragment to 
val mainFragment by fragmentFromFactory<MainFactory>() and remove mainFragment instantiation from onCreate()

If we were using a DI library in our project then we can further reduce the boilerplate of creating factories and let the library handle that for us using constructor injection.

Using Koin library as an example our activity code will look like this

 

 

and we let Koin know of our fragment’s dependency by adding a module to it

 

 

Detailed implementation for Koin can be found here. Something similar can be achieved using multibindings in Dagger, refer to this blog

Well, if everything looks good so far so then why will we require another way of solving the same issue?

 

The limitation of using FragmentFactory is that we can’t pass dynamic arguments to it.¹

 

Let’s say we have a ViewPager that display’s two instances of the same mainFragment but with different textToDisplay values then this won’t be possible using the fragmentFactory implementation.

In that case, we need to provide bundle arguments to the fragment instead

 

2. Bundle arguments

There is nothing new in this, this is how most of us have been using fragments from the get-go.

 

 

What we can do though is create some extension functions to make it a little less awful to work with.

 

 

We can now create a fragment instance like this

 

val mainFragment = MainFragment().withArgs { 
  putString(MainFragment.KEY_TEXT, "Now this won't crash")
}

 

and inside the fragment, we can get the argument value like this

 

private val textToDisplay by argument<String>(KEY_TEXT)

 

Duplication Issue
One problem with creating fragments ourselves without first checking if the fragment exists is that we might end up having duplicate or unattached fragments. This can lead to crashes down the line.

Using fragmentManager.findFragmentByTag(..) we can create another lazy extension to handle that as well.

 

 

In this function, we try to find the fragment by atag and if it returns nullwe use the provided lambda to create the actual fragment.

All we need to do now is check if the fragment is already added before adding it to the fragment manager and our final code will look like this.

 

 

References

[1] https://issuetracker.google.com/issues/136898243#comment24

https://zsmb.co/lets-review-pokedex
https://proandroiddev.com/the-seven-actually-10-cardinal-sins-of-android-development-491d2f64c8e0

https://proandroiddev.com/android-fragments-fragmentfactory-ceec3cf7c959

 

Thanks to Jibin Lawrance. 

 

 

Tags: Android, Fragments, Android App Development, Kotlin, AndroidDev

 

View original article at: 


 

Originally published: November 02, 2020

Android News
Getting… your BottomSheetScaffold working on Jetpack Compose Beta 03
Getting… your BottomSheetScaffold working on Jetpack Compose Beta 03

By Carlos Mota

It’s Monday, no releases this week, and… there’s a new version of Jetpack Compose — beta 03—available. What a perfect time to just increment 02 to 03 and see what’s new. The API is (almost) final so after updating from alpha to beta there weren’t any big changes to do. However, and remember that’s still in development, there’s always something that I need to update. 

By ProAndroidDev -
Android News
Noisy Code 🗣 With Kotlin Scopes
Noisy Code 🗣 With Kotlin Scopes

By Chetan Gupta

Scopes make your code more readable? think again... You are going to encounter these scope functions namely let, run, apply, also, within every Kotlin codebase, along with all the mischievous ways developers exploit their usage from the way they were intended for. Let see how popular opinion on those ends up just as a code noise.

By ProAndroidDev -
Android News
Improving Android DataBinding with Bindables library
Improving Android DataBinding with Bindables library

By Jaewoong Eum

DataBinding is one of the most important factors for MVVM architecture. The basic concept of DataBinding is to link the view and view model via observer patterns, properties, event callbacks, etc. Linking and automating communication between the view via the bound properties or something in the view model has a lot of benefits in the MVVM architecture concept.

By ProAndroidDev -
Android News
KMM QuickStart Guide
KMM QuickStart Guide

By Mayank Kharbanda

Kotlin Multiplatform (KMP) is a code-sharing technology that allows us to use the same code for different platforms whether it’s JVM, Android, iOS, watchOS, tvOS, Web, Desktop, or WebAssembly. In this article, we will use Kotlin Multiplatform Mobile (KMM) which is a subset of KMP with the focus on providing better tooling and support for sharing code on mobile platforms i.e. Android and iOS.

By ProAndroidDev -
droidcon News

Tech Showcases,

Developer Resources &

Partners

/portal/rest/jcr/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/home-details/EmployerBrandingHeader
EmployerBrandingHeader
https://jobs.droidcon.com/
/portal/rest/jcr/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/employerbranding/jobs-droidcon/jobs.droidcon.com
jobs.droidcon.com

Latest Android Jobs

http://www.kotlinweekly.net/
/portal/rest/jcr/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/employerbranding/kotlin-weekly/Kotlin Weekly
Kotlin Weekly

Your weekly dose of Kotlin

https://proandroiddev.com/
/portal/rest/jcr/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/employerbranding/pad/ProAndroidDev
ProAndroidDev

Android Tech Blogs, Case Studies and Step-by-Step Coding

/detail?content-id=/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/employerbranding/Zalando/Zalando
/portal/rest/jcr/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/employerbranding/Zalando/Zalando
Zalando

Meet one of Berlin's top employers

/detail?content-id=/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/employerbranding/Academy for App Success/Academy for App Success
/portal/rest/jcr/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/employerbranding/Academy for App Success/Academy for App Success
Academy for App Success

Google Play resources tailored for the global droidcon community

Follow us

Team droidcon

Get in touch with us

Write us an Email

 

 

Quicklinks

> Code of Conduct

> Terms and Conditions

> How to hold a conference

> FAQs

> Imprint

Droidcon is a registered trademark of Mobile Seasons GmbH Copyright © 2020. All rights reserved.

powered by Breakpoint One