Instance in companion object

176 Views Asked by At

I can't get on with access on the var mBleWrapper: BleWrapper? = null in other activities. There is a predefined Java interface called BleWrapperUiCallbacks, which I suspect contains the functionality I need and the Java-Class BleWrapper.

I tried the Kotlin companion Object, which substitutes the Java singleton, but I would have to set the initialized BleWrapper as companion object and this is not really possible because the BleWrapper is so instantiated:

class BLEActivity : AppCompatActivity() {

     companion object {
     var mBleWrapper: BleWrapper? = null
 //Do something to instantiate the BleWrapper and return the instantiated BleWrapper
 }
 override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.ble_layout)

    initializeBLEWrapper()

    val ble_on = findViewById<FloatingActionButton>(R.id.ble_on)
    ble_on.setOnClickListener {

        val intent = Intent(this, MainActivity::class.java)
        startActivity(intent)
        gatt = mBleWrapper?.getGatt()!!
        c = gatt.getService(NORDIC_UART).getCharacteristic(NORDIC_UART_TX)
        val testVal = "a"
        val bytes = testVal.toByteArray()
        mBleWrapper?.writeDataToCharacteristic(c, bytes)
    }
}

private fun initializeBLEWrapper() {
    mBleWrapper = BleWrapper(this, object : BleWrapperUiCallbacks.Null() {
        override fun uiDeviceFound(
                device: BluetoothDevice,
                rssi: Int,
                record: ByteArray) {              
            if (device.getName() != null) {
                if (device.getName().equals("Adafruit Bluefruit LE") == true) {
                    var status = mBleWrapper!!.connect(device.getAddress().toString())
                    if (status == false) {
                        Log.d("DEBUG", "uiDeviceFound: Connection problem!")
                    } else {
                        Log.d("DEBUG", "Connected")
                        ble_on.isClickable = true
                    }

                }
            }
        }
    }
}

And this "this" refers to the current activity. That's what in Java is solved about Singleton?! Without this instantiation, the BleWrapper is of course always null. The connection to the ble devices in the hole time. This is the logcat: BluetoothGatt: readRssi() And the Service, I need to call is shown in the logcat, too...

Can someone help me? I'm a little desperate. I found also this: Passing an object instance between two activities in Kotlin

0

There are 0 best solutions below