Thursday, May 10, 2018

Android KTX



How to migrate existing java files to Kotlin ?

Here are the steps


  1. Android Studio Menu -> Code -> Convert Java File to Kotlin FileHere is how the functions appears once you convert Java
  2. For Threads & Handler make sure you use inner classes instead function because Kotlin throw a warning saying handler leak,


     

  3. Here is the example code how to use the Handler and thread

    var mIncomingHandler = Handler(IncomingHandlerCallback())

    internal inner class IncomingHandlerCallback : Handler.Callback {
    
        override fun handleMessage(message: Message): Boolean {
    
            swipe_refresh_layout.isRefreshing = false        if (message.what == GetCountryFactsThread.GETCOUNTRYFACTSTHREAD_SUCCESS) {
                val countryFactRespo = message.obj as String
                mCountryModel = ResponseManager.parseCountryFactsRespo(countryFactRespo)
    
                updateAdp(mCountryModel!!)
    
            } else if (message.what == GetCountryFactsThread.GETCOUNTRYFACTSTHREAD_FAIL) {
                //Write code handle if any session expiry            showSnackBar(resources.getString(R.string.no_internet))
            }
            return true    }
    }


    You can call it as below inside the onCreate method of activity

    GetCountryFactsThread(this, mIncomingHandler).start()











0 comments:

Post a Comment