0

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import androidx.core.app.ActivityCompat
import androidx.fragment.app.FragmentActivity
import java.util.*


class PermissionActivity : FragmentActivity() {
    private var mPermissions: ArrayList<String?>? = null
    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        finish()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mPermissions = if (savedInstanceState != null) {
            savedInstanceState.getStringArrayList(PERMISSION_KEY)
        } else {
            ArrayList(Arrays.asList(*intent.getStringArrayExtra(PERMISSION_KEY)))
        }
        Log.i(TAG, "onCreate()")
        requestPermission()
    }

    private fun requestPermission() {
        val it = mPermissions?.iterator()
        if (it != null) {
            while (it.hasNext()) {
                if (ActivityCompat.checkSelfPermission(
                        this,
                        it.next()!!
                    ) == PackageManager.PERMISSION_GRANTED
                ) {
                    it.remove()
                }
            }
        }
        if (mPermissions?.isEmpty() == true) { // all allowed
            setResult(RESULT_OK)
            Log.i(TAG, "finished")
            finish()
        } else {
            var permissions: Array<String?>? = mPermissions?.size?.let { it1 ->
                arrayOfNulls(
                    it1
                )
            }
            permissions = mPermissions?.toArray(permissions)
            if (permissions != null) {
                ActivityCompat.requestPermissions(this, permissions, PERMISSION_REQ_TAG)
            }
            Log.i(TAG, "requestPermissions")
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putStringArrayList(PERMISSION_KEY, mPermissions)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        Log.i(TAG, "onRequestPermissionsResult() requestCode = " + "requestCode")
        if (requestCode == PERMISSION_REQ_TAG) {
            if (permissions.isEmpty()) {
                Log.i(TAG, "onRequestPermissionsResult : permission is 0")
                return
            }
            for (p in grantResults) {
                if (p == PackageManager.PERMISSION_DENIED) {
                    Log.i(TAG, "onRequestPermissionsResult : permission denied")
                    finish()
                    return
                }
            }
            setResult(RESULT_OK)
            finish()
        }
    }

    companion object {
        private val TAG = PermissionActivity::class.java.simpleName
        private const val PERMISSION_KEY = "permissions"
        private const val PERMISSION_REQ_TAG = 1
        fun checkPermission(context: Context?, permissions: Array<String>): Boolean {
            for (permission in permissions) {
                if (context == null || ActivityCompat.checkSelfPermission(
                        context,
                        permission
                    ) == PackageManager.PERMISSION_DENIED
                ) {
                    Log.i(TAG, "checkPermission : PERMISSION_DENIED : " + "permission")
                    return false
                } else {
                    Log.i(TAG, "checkPermission : PERMISSION_GRANTED : " + "permission")
                }
            }
            return true
        }

        fun showPermissionPrompt(
            callingActivity: Activity,
            requestCode: Int,
            permissions: Array<String>
        ) {
            val intent = Intent(callingActivity, PermissionActivity::class.java)
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
            intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION)
            intent.putExtra(PERMISSION_KEY, permissions)
            callingActivity.startActivityForResult(intent, requestCode)
        }
    }
}

the code is shown above and the error is:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.watch, PID: 32569
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.watch/com.example.watch.PermissionActivity}: java.lang.NullPointerException: Attempt to get length of null array
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3456)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3612)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2073)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:246)
        at android.app.ActivityThread.main(ActivityThread.java:7690)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:593)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:995)
     Caused by: java.lang.NullPointerException: Attempt to get length of null array
        at com.example.watch.PermissionActivity.onCreate(PermissionActivity.kt:42)
        at android.app.Activity.performCreate(Activity.java:8033)
        at android.app.Activity.performCreate(Activity.java:8013)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3429)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3612) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2073) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:246) 
        at android.app.ActivityThread.main(ActivityThread.java:7690) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:593) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:995) 
I/Process: Sending signal. PID: 32569 SIG: 9

please help I am trying to give permission through this code but getting error of java.lang.NullPointerException: Attempt to get length of null array at com.example.watch.PermissionActivity.onCreate(PermissionActivity.kt:42) what changes should I make to run this code

Pranay
  • 73
  • 1
  • 6

2 Answers2

0

You are using mPermissions!!.size and It seems that mPermissions is null, you should debug to check why it's null. Also try to avoid using !! and instead do null checks either with if statement or scope functions

  • how should i proceed as i have no idea what to do, this is not my code I am just using it in my app @marcpetitvecino – Pranay Jan 13 '23 at 07:39
  • In your onCreate() method when you set the value for `mPermissions`, you are getting a String array extra with the key `PERMISSION_KEY`, this means you must navigate to this class putting an `Extra` in the `Intent`. If you look at the bottom of the class, inside your `companion object` you have a `showPermissionPrompt()` function, you must use this function with the needed parameters: your origin Activity, the requestCode for the latter `onActivityResult` and the String array with the permissions. – marcpetitvecino Jan 13 '23 at 08:35
  • You must call this `showPermissionPrompt()` from your previous activity, if you check the function you will see it adds the `PERMISSION_KEY` Extra right there. – marcpetitvecino Jan 13 '23 at 08:39
  • I tried and also removed !! and applied null checks but still got the same error. – Pranay Jan 13 '23 at 11:10
0

Based on your stack trace, the line in error appears to be if (mPermissions!!.isEmpty()) . As the Kotlin docs state here, the !! operator is for NPE-lovers and should be avoided. Since it appears that you're just attempting to just check to see if your array of permissions is empty, you could use mPermissions.isNullOrEmpty() instead.

scottt
  • 8,301
  • 1
  • 31
  • 41
  • I have already removed !! but still getting the same error and I have updated the code – Pranay Jan 13 '23 at 18:36
  • i am getting error in this line ArrayList(Arrays.asList(*intent.getStringArrayExtra(PERMISSION_KEY))) that is 5th line oncreate. please help @scottt – Pranay Jan 13 '23 at 18:37
  • Since mPermissions can be null, you can't just attempt to test it's length via isEmpty(). You have to check for null first. You can do that by wrapping it in an if-block or you can use the function I mentioned in my answer, isNullOrEmpty(). – scottt Jan 16 '23 at 21:46