Linting functions that need to be called from specific lifecycle methods

google: lint

Repeatedly, I made few mistakes while using the new registerForActivityResultAPI, 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)

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 registerForActivityResultoutside onCreateor onAttachlifecycle functions in Fragmentor Activitysubclasses.

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 stacks are not considered, also calls inside lambdas remain unchecked.

--

--