尝试在空对象引用上调用虚拟方法“android.content.AttributionSource android.content.Context.getAttributionSource()”

Attempt to invoke virtual method 'android.content.AttributionSource android.content.Context.getAttributionSource()' on a null object reference

提问人:Bertrandho 提问时间:11/13/2023 更新时间:11/13/2023 访问量:29

问:

我正在尝试访问AllowingAccessCamera类中的函数,但我收到上述错误,但是当我自己测试AllowingAccessCamera代码时,它工作正常。

package com.example.mindsync

// IntroActivity.kt
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity

class IntroActivity : AppCompatActivity() {

    private lateinit var sharedPreferences: SharedPreferences
    private lateinit var permissions: AllowingAccessCamera
    private var currentScreen = 1
    private val totalScreens = 2  // Set the total number of introductory screens


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        sharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE)

        // Check if the app is opened for the first time
        if (isFirstTime()) {
            // If it's the first time, show the introductory screens
            showIntroScreen()
        } else {
            // If not the first time, navigate to the main activity or any other desired activity
            startActivity(Intent(this, MainActivity::class.java))
            finish()
        }
    }

    private fun isFirstTime(): Boolean {
        return sharedPreferences.getBoolean("firstTime", true)
    }

    private fun showIntroScreen() {

        // Set the layout for the current intro screens
        when (currentScreen) {
            1 -> setContentView(R.layout.getting_started)
            2 -> setContentView(R.layout.allowing_access_to_camera)
        }

        // Set a click listener on the current screen to move to the next screen
        findViewById<Button>(R.id.getting_started)?.setOnClickListener {
            handleIntroButtonClick()
        }

        findViewById<Button>(R.id.cam_request_permission)?.setOnClickListener {

            permissions = AllowingAccessCamera(this)

            // Permission is not granted, request it
            permissions.requestCameraPermission()
        }
    }


     private fun handleIntroButtonClick() {
            if (currentScreen < totalScreens) {
                currentScreen++
                showIntroScreen()
            } else {
                // Check if the activity is in a valid state
                // Mark that the app has been opened
                val editor = sharedPreferences.edit()
                editor.putBoolean("firstTime", false)
                editor.apply()

                //Transition animation
                overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)

                // Last screen reached, navigate to the main activity
                startActivity(Intent(this, MainActivity::class.java))
            }
    }

}

package com.example.mindsync

import android.Manifest
import android.content.pm.PackageManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.core.app.ActivityCompat

class AllowingAccessCamera(introActivity: IntroActivity) : AppCompatActivity() {

    private val CAMERA_PERMISSION_REQUEST_CODE = 100

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

    }

    fun requestCameraPermission() {
        ActivityCompat.requestPermissions(
            this,
            arrayOf(Manifest.permission.CAMERA),
            CAMERA_PERMISSION_REQUEST_CODE
        )
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == CAMERA_PERMISSION_REQUEST_CODE) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission is granted, proceed with camera-related operations
                showToast(getString(R.string.camera_permission_granted))
            } else {
                // Permission is denied, handle accordingly
                // You may want to show a message to the user or disable camera-related features
                showToast(getString(R.string.camera_permission_not_granted))
            }
        }
    }

    private fun showToast(message: String) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
    }



}

我尝试在 IntroActivity 类中初始化它,但我不断得到空对象引用,问题出在代码权限 = AllowingAccessCamera(this) 上。

谢谢

Android Kotlin Mobile null 移动应用程序

评论

0赞 Selvin 11/13/2023
永远不要自己创建android组件的实例...

答:

0赞 Blundell 11/13/2023 #1

你不能/不应该以这种方式实例化一个活动:

        findViewById<Button>(R.id.cam_request_permission)?.setOnClickListener {

            permissions = AllowingAccessCamera(this)

            // Permission is not granted, request it
            permissions.requestCameraPermission()
        }

您应该在“活动”之间导航:

https://medium.com/swlh/navigate-between-activities-in-android-studio-c7f4617e7388

Intent i = new Intent(IntroActivity.this, AllowingAccessCamera.class);
startActivity(i);

或者你需要重构为不是一个 Activity 并且不扩展。AllowingAccessCameraAppCompatActivity

即做一些更简单的事情:

findViewById<Button>(R.id.cam_request_permission)?.setOnClickListener {
  ActivityCompat.requestPermissions(
            this,
            arrayOf(Manifest.permission.CAMERA),
            CAMERA_PERMISSION_REQUEST_CODE
        )
}