skip to Main Content

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

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search