【问题标题】:Kotlin How to init BluetoothDeviceKotlin 如何初始化蓝牙设备
【发布时间】:2018-08-06 01:51:23
【问题描述】:

我想在我的项目中使用蓝牙打印机,但是我收到了这个错误

  lateinit property mmDevice has been not initialized

这是我的代码

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()
    }
}

如何在 koltin 中初始化蓝牙设备?,我尝试了一些解决方案,但它不起作用

【问题讨论】:

  • 您确定错误来自这一行吗?您没有在代码中的任何其他位置使用mmDevice
  • 同意@Christopher。无论如何,您可以将 mmDevice 更改为可空类型并摆脱 lateinit: var mmDevice: BluetoothDevice? = null

标签: android bluetooth kotlin kotlin-lateinit


【解决方案1】:

我认为,您没有发布所有代码并将我们指向发生错误的错误行。仅当您尝试访问未初始化的 lateinit 属性时才会发生此错误。我可以想象,你的 findBT 方法没有找到任何合适的设备,所以你的 mmDevice 没有初始化。

只有当你 100% 确定时才应该使用 lateinit,该属性将在第一次使用之前被初始化。搜索 BT 设备 - 不是那种情况。所以我建议你改变那一行:

lateinit var mmDevice: BluetoothDevice

到那一行:

var mmDevice: BluetoothDevice? = null

并在您的代码中对其使用空值检查或安全调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-16
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2014-07-16
    • 1970-01-01
    • 2014-10-04
    相关资源
    最近更新 更多