I have a class that makes bluetooth connection and gets a PID from an OBD bluetooth dongle that its connected in the car. But when calling the method for getting RPM then I have an Exception about not initialazing that property.
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
}
}
This is how I call the method from another class
BluetoothOBDManager().connect(deviceString)
var rpm = BluetoothOBDManager().getCurrentRpm()
rpmTextView.setText(rpm)
The exception
E/AndroidRuntime: FATAL EXCEPTION: main
Process: gr.obd.logger, PID: 17486
kotlin.UninitializedPropertyAccessException: lateinit property rpmCommand has not been initialized
I have tried to INIT the property inside the method but no luck
override fun getCurrentRpm(): Int {
rpmCommand = RPMCommand()
rpmCommand.run(input, output) // This line throughs the EXCEPTION
return rpmCommand.rpm
}
BluetoothOBDManager().connect(deviceString)
var rpm = BluetoothOBDManager().getCurrentRpm()
Your code creates a BluetoothOBDManager
, connects it (initializing rpmCommand
), then throws it away, creates a new BluetoothOBDManager
with everything uninitialized and tries to call getCurrentRpm
on it. It likely should be
val obdManager = BluetoothOBDManager()
obdManager.connect(deviceString)
val rpm = obdManager.getCurrentRpm()
This doesn't explain why you would get
I have tried to INIT the property inside the method but no luck
but that really shouldn't happen; I expect something else is going wrong.