2

I want to use bluetooth printer in my project, but I got this error

  lateinit property mmDevice has been not initialized

This is my code

lateinit var device:String
lateinit var mBluetoothAdapter: BluetoothAdapter
lateinit var mmSocket: BluetoothSocket
lateinit var mmDevice: BluetoothDevice

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_penjualan_cetak)

    device = Function().getShared("printer","",this)

    try {
        findBT()
    } catch (e: Exception) {

    }
}

fun findBT(){
    try{
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()

        val paireddevice = mBluetoothAdapter.bondedDevices

        if(paireddevice.size > 0){
            ePrinter.setText("Printer Belum Dipilih")
            for (device:BluetoothDevice in paireddevice) {
                if (device.name == this.device) {
                    // this is the error come from
                    mmDevice = device
                    break
                }
            }
        }
    }catch (e:Exception){
        e.printStackTrace()
    }
}

How can I init the bluetoothdevice in koltin?, I have tried some solution but it not works

Firman
  • 21
  • 3
  • Are you sure the error is coming from this line? You don't use `mmDevice` at any other position in your code? – Christopher Nov 20 '18 at 13:17
  • Agree with @Christopher. Anyway you can change your mmDevice to nullable type and get rid of lateinit: var mmDevice: BluetoothDevice? = null – Andrei Vinogradov Nov 20 '18 at 13:20

1 Answers1

0

I think, that you did not post all your code and point us to a wrong line where error happen. This error can occur only when you trying to access not initialized lateinit property. I can imagine, that your findBT method is not finding any sutable device, so your mmDevice is not initialized.

You should use lateinit only when you 100% sure, that property will be initialized before first use. Searching BT device - not that case. So I suggest you to change that line:

lateinit var mmDevice: BluetoothDevice

to that line:

var mmDevice: BluetoothDevice? = null

and use null-checks or safe calls on it in your code.

Andrei Vinogradov
  • 1,865
  • 15
  • 32