点击Medir按钮触发java.lang.NullPointerException问题求助
解决Medir按钮点击崩溃的空指针异常问题
问题描述
每次点击Medir按钮时应用崩溃,抛出异常:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
其余功能正常,已尝试更换系统、Android版本及重写代码,问题仍未解决。
核心问题定位
崩溃根源在Medir Activity的selectDeviceList初始化时机错误:在Activity类的成员变量位置直接调用findViewById,此时Activity的Context尚未初始化,导致selectDeviceList为null,后续使用时触发空指针异常。
修复步骤
1. 修正ListView初始化时机
将selectDeviceList的声明改为延迟初始化,并在onCreate方法中完成赋值:
- 成员变量位置修改:
private lateinit var selectDeviceList: ListView - 在
onCreate方法的setContentView(R.layout.activity_medir)之后添加:selectDeviceList = findViewById(R.id.selectorLV)
2. 补全蓝牙权限申请逻辑
原代码仅检查权限但未申请,需添加权限申请流程避免后续蓝牙操作失败:
在pairedDeviceList方法中补充:
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.BLUETOOTH_CONNECT), 100) return }
同时添加权限回调处理:
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == 100) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { pairedDeviceList() } else { Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show() } } }
3. 修正MainActivity数据库查询逻辑(非崩溃根源,但属于功能问题)
原代码中bd.rawQuery(...).toString()获取的是Cursor对象的字符串表示,而非实际查询数据,需正确处理Cursor:
val nameCursor = bd.rawQuery("SELECT nombre FROM usuario", null) val name = if (nameCursor.moveToFirst()) nameCursor.getString(0) else "" nameCursor.close() val weightCursor = bd.rawQuery("SELECT peso FROM usuario", null) val weight = if (weightCursor.moveToFirst()) weightCursor.getString(0) else "" weightCursor.close()
修改后的完整Medir Activity代码
package com.example.kotlincalcinsu import android.Manifest import android.bluetooth.BluetoothAdapter import android.bluetooth.BluetoothDevice import android.content.Intent import android.content.pm.PackageManager import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Button import android.widget.ListView import android.widget.Toast import androidx.core.app.ActivityCompat class Medir : AppCompatActivity() { private val REQUEST_CODE_ENABLE_BT: Int = 1 private var bluetoothAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter() private lateinit var pairedDevices: Set<BluetoothDevice> private lateinit var selectDeviceList: ListView companion object { val EXTRA_ADDRESS: String = "Device_address" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_medir) selectDeviceList = findViewById(R.id.selectorLV) val refresh = findViewById<Button>(R.id.refresh) val conectar = findViewById<Button>(R.id.conectar) if (bluetoothAdapter == null) { Toast.makeText(this, "This device doesn't support Bluetooth", Toast.LENGTH_LONG).show() return } else { Toast.makeText(this, "Bluetooth available", Toast.LENGTH_LONG).show() } if (!bluetoothAdapter!!.isEnabled) { val enableBluetoothIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE) if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.BLUETOOTH_CONNECT), 100) return } startActivityForResult(enableBluetoothIntent, REQUEST_CODE_ENABLE_BT) } refresh.setOnClickListener { pairedDeviceList() } } private fun pairedDeviceList() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.BLUETOOTH_CONNECT), 100) return } pairedDevices = bluetoothAdapter!!.bondedDevices val list: ArrayList<BluetoothDevice> = ArrayList() if (pairedDevices.isNotEmpty()) { for (device: BluetoothDevice in pairedDevices) { list.add(device) Log.i("device", "" + device) } } else { Toast.makeText(this, "No paired Bluetooth devices", Toast.LENGTH_LONG).show() } val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, list) selectDeviceList.adapter = adapter selectDeviceList.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ -> val device: BluetoothDevice = list[position] val address: String = device.address val intent = Intent(this, ControlActivity::class.java) intent.putExtra(EXTRA_ADDRESS, address) startActivity(intent) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == REQUEST_CODE_ENABLE_BT) { if (resultCode == RESULT_OK) { if (bluetoothAdapter!!.isEnabled) { Toast.makeText(this, "Bluetooth has been enabled", Toast.LENGTH_LONG).show() } else { Toast.makeText(this, "Bluetooth has been disabled", Toast.LENGTH_LONG).show() } } else if (resultCode == RESULT_CANCELED) { Toast.makeText(this, "Bluetooth enabling has been canceled", Toast.LENGTH_LONG).show() } } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == 100) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { pairedDeviceList() } else { Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show() } } } }
内容的提问来源于stack exchange,提问作者Angel Estrada
相关产品推荐
相关产品推荐

