Shaik Jaleel
Shaik Jaleel

Reputation: 31

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

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()
            }

        }

    }

Upvotes: 2

Views: 3352

Answers (3)

Shaik Jaleel
Shaik Jaleel

Reputation: 31

STORAGE ACCESS PERMISSION SAF (MEDIUM)

if (files?.isNotEmpty() == true) { 

added this in code and added permission android:requestLegacyExternalStorage="true" in manifest file

Upvotes: 1

Alexey Romanov
Alexey Romanov

Reputation: 170713

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.

Upvotes: 0

Hack5
Hack5

Reputation: 3601

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

Upvotes: 1

Related Questions