how to fix this Unsafe use of a nullable receiver of type Array?

Viewed 2796

It's a whatsapp story saver app. Till Android 9 it's fine, but when I tried to use it on Android 10 it's crashing with the below stack trace:

java.lang.IllegalStateException: files must not be null
    at com.shaikjaleel.wsave.fragments.VideosFragment$loadStories$1$1.invoke(VideosFragment.kt:84)
    at com.shaikjaleel.wsave.fragments.VideosFragment$loadStories$1$1.invoke(VideosFragment.kt:30)
    at org.jetbrains.anko.AsyncKt$uiThread$1.run(Async.kt:70)

also android studio throws this warning ( Unsafe use of a nullable receiver of type Array<File!>?

VideoFragment.kt

    private fun loadStories() {
        if (!storagePermissionGranted()) {
            toast(getString(R.string.message_permissions_required))
            stopRefreshing()
            return
        }

        val dir = File(K.WHATSAPP_STORIES)
        if (!dir.exists())
            dir.mkdirs()

        doAsync {
            val files = dir.listFiles { _, s ->
                s.endsWith(".mp4") || s.endsWith(".gif") }

            uiThread {

                if (files.isNotEmpty()) {
                    hasStories()

                    for (file in files.sortedBy { it.lastModified() }.reversed()) {
                        val story = Story(K.TYPE_VIDEO, file.absolutePath)
                        adapter.addStory(story)
                    }

                } else {
                    noStories()
                }

                stopRefreshing()
            }

        }

    }
3 Answers

Change if (files.isNotEmpty()) { to if (files?.isEmpty() != false) {

I am not sure why this

Unsafe use of a nullable receiver of type Array<File!>?

is just a warning instead of an error. I also assume line 84 in the error message is

if (files.isNotEmpty()) {

If so, I'd rewrite it as

if (files != null && files.isNotEmpty())

Or

if (files?.isNotEmpty() ?: false)

but I think the first one is cleaner.

Related