提问人:Angel Estrada 提问时间:11/4/2022 更新时间:11/5/2022 访问量:140
错误:java.lang.NullPointerException,需要任何帮助才能使其工作 [重复]
Error: java.lang.NullPointerException, need any help on getting it to work [duplicate]
问:
每次按下 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。我重写了代码以检查是否存在一些输入错误或文件是否有问题,但没有任何效果。
答:
1赞
Tenfour04
11/4/2022
#1
像这些行这样的内容:
private var bluetoothAdapter: BluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
val selectDeviceList = findViewById<ListView>(R.id.selectorLV)
将导致崩溃。无法在属性初始值设定项中安全地调用 Activity 函数,因为在调用之前尚未设置 Activity。属性初始值设定项在 之前调用。onCreate()
onCreate
您需要将这些属性更改为 并在 中初始化它们,或者您可以将它们转换为 Lazy 属性 -- 替换为 。lateinit
onCreate
= /*...*/
by lazy { /*...*/ }
为了便于将来参考,堆栈跟踪为您提供了导致问题的确切代码行。如果将来遇到无法解决的问题,则需要发布堆栈跟踪和堆栈跟踪引用的代码。
评论
0赞
Angel Estrada
11/4/2022
谢谢,将尝试将 lateinit 添加到其中。这是应用程序崩溃时的 logcat 结果,我没有添加代码,因为据我所知,它没有显示错误在哪里。我认为意图有问题,因为该应用程序甚至无法启动 Medir 活动,只是无法弄清楚它是什么。
0赞
Angel Estrada
11/4/2022
这是我得到的 logcat 结果的一部分 E/AndroidRuntime:致命异常:主进程:com.example.kotlincalcinsu,PID:8835 java.lang.RuntimeException:无法实例化活动 ComponentInfo{com.example.kotlincalcinsu/com.example.kotlincalcinsu.Medir}:java.lang.NullPointerException:尝试在 android.app.ActivityThread 的空对象引用上调用虚拟方法“android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()”。执行启动活动(ActivityThread.java:3914)
0赞
Tenfour04
11/4/2022
我认为你上面的一行代码是问题的根源,但它会导致误导,所以异常被抛出在堆栈的更上层的代码中,在Android的类中。如果进一步阅读堆栈跟踪,可能会找到以“at”开头的一行,该行描述了您自己的文件中上述两行之一。
评论
null.getApplicationInfo()