Beginning Recycler View - Part 7: Challenge: | Ray Wenderlich

Take all the basics of RecyclerView that you've learned so far to build a Favorites screen for the sample app.

This is a companion discussion topic for the original entry at


In the video (Time: 02:46), line 37, there is this line:
val favorites = CreatureStore.getFavoriteCreatures(activity)

When I tried running the code, I got an error saying: Type mismatch: inferred type is FragmentActivity? but Context was expected. I checked the end project and found this line instead.
val favorites = CreatureStore.getFavoriteCreatures(context!!)

I’m curious why this happened and was not sure what the distinction between activity and context is. I purchased the Android Avalanche Bundle but started off with the videos. If there is a particular part of the book or other video that explains this concept a bit more in depth, please kindly let me know about it. Thanks!

Hi ijl0322! Thanks for the question! :] There’s a subtle distinction going on here that changed in the Android SDK while this course was under development.

The CreatureStore.getFavoriteCreatures(context: Context) method takes a non-nullable Context as its argument. An Activity is a Context since it extends from Context, so in theory could be passed into the method. But it looks now like the activity property of a Fragment results in a nullable FragmentActivity?.

So the main issue here is that the activity property is nullable, so it can’t be passed into getFavoriteCreatures() which needs a non-nullable argument. In the final code we’re using a different context property (that is, instead of activity), and we’re using the not-null assertion operator !! to pass it as non-nullable.

I hope that clears this up a bit, but thanks for the question and great catch finding this in the code.

Hi macsimus!

Thank you for replying! If I understand this correctly, the reason that activity cannot be used is because it’s nullable. And using val favorites = CreatureStore.getFavoriteCreatures(activity!!) actually runs without error. Is there a reason to choose context!! over activity!! ? Thank you!

Yep, the nullability is coming from Java/Kotlin interop. You can see this in part by Cmd-clicking on activity to go into the Java code (if you have it installed in Android Studio) which has no nullablity annotations.

The fragment activity property in Kotlin is really a call to getActivity() which has been around since Fragments were introduced. The fragment context property is really a call to getContext(), which was added in API 23 and the associated fragment support library, so it’s a little newer. For this use case, you can use either activity!! or context!!, and the result is the same.