Search code examples
androidandroid-studiokotlinpermissionsnullpointerexception

Permission java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()'


I am runnning an error about setting permission. I declared location and internet permissions in my Manifest and called checkPermission() and onRequestPermissionsResult to display permission dialog. However, I can not start my application and am receiving the same error.

I have tried

private val hasFineLocationPermission = ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)

I changed context of the line above as applicationContext, this@MainActivity, MainActivity@This, but I still receive the same error.

MainActivity

class MainActivity : AppCompatActivity() {

private lateinit var binding : ActivityMainBinding

private var REQUIRED_PERMISSIONS = arrayOf<String>(
    Manifest.permission.ACCESS_FINE_LOCATION,
    Manifest.permission.ACCESS_BACKGROUND_LOCATION)

private val context : Context = applicationContext
private val hasFineLocationPermission = ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
private val hasBackgroundLocationPermission = ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_BACKGROUND_LOCATION)

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    checkPermission()
}

fun checkPermission() {
    if (hasFineLocationPermission == PackageManager.PERMISSION_GRANTED
    ) {
        // Fine Location permission is granted
        // Check if current android version >= 11, if >= 11 check for Background Location permission
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (hasBackgroundLocationPermission == PackageManager.PERMISSION_GRANTED
            ) {
                // Background Location Permission is granted so do your work here
            } else {
                // Ask for Background Location Permission
                askPermissionForBackgroundUsage()
            }
        }
    } else {
        // Fine Location Permission is not granted so ask for permission
        askForLocationPermission();
    }
}

private fun askForLocationPermission() {
    if (ActivityCompat.shouldShowRequestPermissionRationale(this@MainActivity,
            Manifest.permission.ACCESS_FINE_LOCATION)
    ) {
        AlertDialog.Builder(this)
            .setTitle("Permission Needed!")
            .setMessage("Location Permission Needed!")
            .setPositiveButton("OK", DialogInterface.OnClickListener { dialogInterface, int ->
                ActivityCompat.requestPermissions(this@MainActivity, arrayOf(
                    Manifest.permission.ACCESS_FINE_LOCATION), hasFineLocationPermission)
            })
            .setNegativeButton("CANCEL", DialogInterface.OnClickListener { dialogInterface, int ->
                // Permission is denied by the user
                throw RuntimeException("denied")
            })
            .create().show()
    } else {
        ActivityCompat.requestPermissions(this,
            arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), hasFineLocationPermission)
    }
}

private fun askPermissionForBackgroundUsage() {
    if (ActivityCompat.shouldShowRequestPermissionRationale(this@MainActivity,
            Manifest.permission.ACCESS_BACKGROUND_LOCATION)
    ) {
        AlertDialog.Builder(this)
            .setTitle("Permission Needed!")
            .setMessage("Background Location Permission Needed!, tap \"Allow all time in the next screen\"")
            .setPositiveButton("OK", DialogInterface.OnClickListener { dialogInterface, int ->
                ActivityCompat.requestPermissions(this@MainActivity,
                    arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION), hasBackgroundLocationPermission)
            })
            .setNegativeButton("CANCEL", DialogInterface.OnClickListener { dialogInterface, int ->
                // Permission is denied by the user
                throw RuntimeException("denied")
            })
            .create().show()
    } else {
        ActivityCompat.requestPermissions(this,
            arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION), hasBackgroundLocationPermission)
    }
}

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults)

 //        if (requestCode == PERMISSIONS_REQUEST_CODE && grantResults.size == 
   REQUIRED_PERMISSIONS.size) {
    if (requestCode ==  hasFineLocationPermission) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){
                if (hasBackgroundLocationPermission == PackageManager.PERMISSION_GRANTED) {
   //                        var check_result = true
   //                        for (result in grantResults) {
   //                            if (result != PackageManager.PERMISSION_GRANTED) {
   //                                check_result = false;
   //                                break;
   //                            }
  //                        }
                } else {
                    askPermissionForBackgroundUsage()
                }
            }
        } else {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    REQUIRED_PERMISSIONS[0])
            ) {
                Toast.makeText(this,
                    "denied",
                    Toast.LENGTH_SHORT).show()
                finish()
            } else {
                Toast.makeText(this, "denied", Toast.LENGTH_SHORT)
                    .show()
            }
        }
    } else if (requestCode == hasBackgroundLocationPermission) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // User granted for Background Location Permission.
        } else {
            ActivityCompat.shouldShowRequestPermissionRationale(this,
                REQUIRED_PERMISSIONS[1])
        }
    }
}
}

Solution

  • Activities aren't initialized until onCreate is called. This means you can't use functions like getApplicationContext until then. Basically, Activities should never have init blocks. They should run everything in onCreate if it relies on a Context.