DEV Community

Cover image for Linting functions that need to be called from specific lifecycle method
Nikola Despotoski
Nikola Despotoski

Posted on

Linting functions that need to be called from specific lifecycle method

Repeatedly, I made few mistakes while using the new registerForActivityResult API, resulting in error:

Fatal Exception: java.lang.IllegalStateException: Fragment MyFragment{e964a6} (573498bb-7d87-4d58-9e84-59223f13f14c) id=0x7f0a00b3} is attempting to registerForActivityResult after being created. Fragments must call registerForActivityResult() before they are created (i.e. initialization, onAttach(), or onCreate()).
       at androidx.fragment.app.Fragment.prepareCallInternal(Fragment.java:3)
       at com.package.name.android.ui.MyFragment.registerForActivityResult(MyFragment.java:15)
Enter fullscreen mode Exit fullscreen mode

Developers should be provided with compile-time lint error or/and Code Inspections for such specific misuse of lifecycle-sensitive function calls.

I wrote myself one to remind me that I'm ending up in usability issue. This lint check searches for usage of registerForActivityResult outside onCreate or onAttach lifecycle functions in Fragment or Activity subclasses.

It considers unary expressions, such as:

registerForActivityResult(contract, callback).launch(argument)

and binary expressions:

launcher = registerForActivity(contract, callback)

which object will be used to call launch(arguments) .

This lint won't show warning, if function call is made in another function, unfortunately deeper function stack is not considered, also calls inside lambdas remains unchecked.

Top comments (0)