每次按下按鈕 Medir 時,我都會收到此錯誤,其他一切正常
原因:java.lang.NullPointerException:嘗試在空物件參考上呼叫虛擬方法 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()'
這是 MainActivity 代碼:
package com.example.kotlincalcinsu
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val admin = AdminSQLiteOpenHelper(this, "AppDB", null, 1)
val bd = admin.readableDatabase
val name = bd.rawQuery("SELECT nombre FROM usuario", null).toString()
val weight = bd.rawQuery("SELECT peso FROM usuario", null).toString()
bd.close()
//declarando TextView
val nombre = findViewById<TextView>(R.id.Nombre)
val peso = findViewById<TextView>(R.id.Peso)
//declarando botones
val medir = findViewById<Button>(R.id.medir)
val historial = findViewById<Button>(R.id.historial)
val registro = findViewById<Button>(R.id.registro)
if (name.isNotEmpty() && weight.isNotEmpty()){
nombre.text = name
peso.text = weight
}
medir.setOnClickListener {
val intent = Intent(this, Medir::class.java)
startActivity(intent)
}
historial.setOnClickListener {
val intent = Intent(this, Historial::class.java)
startActivity(intent)
}
registro.setOnClickListener {
val intent = Intent(this, Registro::class.java)
startActivity(intent)
}
}
}
這是我要開始的活動
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>
val selectDeviceList = findViewById<ListView>(R.id.selectorLV)
companion object{
val EXTRA_ADDRESS: String = "Device_address"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_medir)
val refresh = findViewById<Button>(R.id.refresh)
val conectar = findViewById<Button>(R.id.conectar)
//inicializar BluetoothAdapter
//bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
//revisar si esta encendido el Bluetooth
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) return
startActivityForResult(enableBluetoothIntent, REQUEST_CODE_ENABLE_BT)
}
refresh.setOnClickListener { pairedDeviceList() }
}
private fun pairedDeviceList(){
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { }
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 enableing has been canceled", Toast.LENGTH_LONG).show()
}
}
}
}
and the AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-feature
android:name="android.hardware.bluetooth_le"
android:required="true">
</uses-feature>
<uses-feature
android:name="android.hardware.bluetooth"
android:required="true">
</uses-feature>
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.KotlinCalcInsu"
tools:targetApi="31">
<activity
android:name=".Historial"
android:exported="false">
<meta-data
android:name="android.app.lib_name"
android:value="" />
</activity>
<activity
android:name=".Medir"
android:exported="false">
<meta-data
android:name="android.app.lib_name"
android:value="" />
</activity>
<activity
android:name=".Registro"
android:exported="false">
<meta-data
android:name="android.app.lib_name"
android:value="" />
</activity>
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.app.lib_name"
android:value="" />
</activity>
</application>
</manifest>
根據老師和其他看過它的人的說法,一切似乎都是正確的,但它只是不斷拋出該錯誤并使應用程式崩潰。歡迎任何幫助,并在此先感謝
我已經嘗試過不同的計算機 Mac 和 Windows,嘗試過不同版本的 Android 和 Android Studio。我重寫了代碼以檢查是否有一些打字錯誤或檔案有問題,但沒有任何效果。
uj5u.com熱心網友回復:
像這些行的任何東西:
private var bluetoothAdapter: BluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
val selectDeviceList = findViewById<ListView>(R.id.selectorLV)
在 Activity 中會導致崩潰。您不能在屬性初始化程式中安全地呼叫 Activity 函式,因為在呼叫之前尚未設定 Activity onCreate()。屬性初始化器在之前被呼叫onCreate。
您要么需要將它們更改為lateinit并在其中初始化它們onCreate,要么可以將它們轉換為 Lazy 屬性 - 替換= /*...*/為by lazy { /*...*/ }.
為了將來參考,堆疊跟蹤為您提供了導致問題的確切代碼行。如果您將來遇到無法解決的問題,則需要發布堆疊跟蹤和堆疊跟蹤參考的代碼。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/526764.html
上一篇:如何解釋高昂的前端實體成本?
