我有一个进行蓝牙连接的类,并从与汽车相连的OBD蓝牙加密狗获取PID。 但是,当调用获取RPM的方法时,我有一个关于不初始化该属性的异常。
class BluetoothOBDManager : OBDManager {
lateinit var context: Context
private lateinit var input: InputStream
private lateinit var output: OutputStream
private lateinit var rpmCommand: RPMCommand
private lateinit var coolantTempCommand: EngineCoolantTemperatureCommand
private lateinit var airIntakeTempCommand: AirIntakeTemperatureCommand
private lateinit var mmSocket : BluetoothSocket
fun connect(deviceString: String) {
var adapter: BluetoothAdapter = getDefaultAdapter()
val device = adapter.getRemoteDevice(deviceString)
val uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")
val mmSocket:BluetoothSocket=device.createRf....Record(uuid)
mmSocket.let { socket ->
socket.connect()
}
input = mmSocket.inputStream
output = mmSocket.outputStream
if (mmSocket.isConnected) {
println("output.write =1")
output.write(1)
}
rpmCommand = RPMCommand() //This is the INIT of the propert
}
override fun getCurrentRpm(): Int {
rpmCommand.run(input, output) // This line throughs the EXCEPTION
return rpmCommand.rpm
}
}
这是我从另一个类调用该方法的方式
BluetoothOBDManager().connect(deviceString)
var rpm = BluetoothOBDManager().getCurrentRpm()
rpmTextView.setText(rpm)
例外
E/AndroidRuntime: FATAL EXCEPTION: main
Process: gr.obd.logger, PID: 17486
kotlin.UninitializedPropertyAccessException: lateinit property rpmCommand has not been initialized
我尝试初始化方法中的属性,但没有运气
override fun getCurrentRpm(): Int {
rpmCommand = RPMCommand()
rpmCommand.run(input, output) // This line throughs the EXCEPTION
return rpmCommand.rpm
}
答案 0 :(得分:0)
BluetoothOBDManager().connect(deviceString)
var rpm = BluetoothOBDManager().getCurrentRpm()
您的代码创建一个BluetoothOBDManager
,将其连接(初始化rpmCommand
),然后将其丢弃,创建一个未初始化所有内容的 new BluetoothOBDManager
并尝试致电getCurrentRpm
。可能应该是
val obdManager = BluetoothOBDManager()
obdManager.connect(deviceString)
val rpm = obdManager.getCurrentRpm()
这并不能说明您为什么得到
我试图初始化方法中的属性,但是没有运气
但是真正的 不应该发生;我预计会有其他问题。