

Imagine for a moment that you’re a super villain. In many ways, they have functionality similar to activities. As the name would suggest, fragments are not independent entities, but are tied to a single activity. Huyen Tue Dao wrote the original tutorial.Ī fragment is an Android component that holds part of the behavior and/or UI of an activity. If you were actually unsure of whether activity could be null, you would have a fallback action to take in the flow of how your app behaves to the user.īut in actuality, we know the activity is not null during onResume, so you can use requireActivity().Update note: Aaqib Hussain updated this tutorial for Kotlin and Android Studio 3.3.

If that were actually possible, your code would not start the camera and would not check permissions, so you'd just have kind of blank screen with no feedback to the user why nothing is happening indefinitely. You demonstrate with ?.let that you are unsure if activity might be null, and you don't want to do anything if it is null. It, permissions.toTypedArray(), permissionsRequestCode Also, since !! is so often a code smell, these functions help show your intent more deliberately without alarming anyone that's reviewing your code. However, Android provides requireContext() and requireActivity() functions that are preferable to context!! and activity!!, because they will provide better error messages if you use them in the wrong place. Incidentally, we know from the documentation of the Fragment lifecycle that context will not be null during lifecycle functions like onResume, so context!! is safe. If you know it's not null, you should be bold and use it at the source like this: !hasPermissions(context!!) Either you know the object is not null or you don't, but this code simultaneously communicates that you're not sure ( ?.) and then says that you are sure ( !!). You use a null-safe call followed by a non-null assertion. Import .getOutputDirectoryĬlass CameraActivityFragment : Fragment() !! Here is a fragment I would like some feedback on so I can writer safer and better Kotlin code. Just started with Kotlin and Android CameraX.
