Home > database >  Async Task is Deprecated -- Geocode Address -- Get Address from Lat and Long -- Kotlin -- Android
Async Task is Deprecated -- Geocode Address -- Get Address from Lat and Long -- Kotlin -- Android

Time:06-05

This is for a personal project that I am working on in Android Studio with Kotlin. I am having trouble understanding how to fix this deprecated code for an Asynctask that gets a Geocode address. if anyone can help me out with this to find a different way to achieve this, i would be very grateful.

If there are anything more i can provide to make this issue any clearer please let me know!

class GetAddressFromLatLng(
context: Context, private val latitude: Double,
private val longitude: Double) : AsyncTask<Void, String, String>() {

/**
 * Constructs a Geocoder whose responses will be localized for the
 * given Locale.
 *
 * @param context the Context of the calling Activity
 * @param locale the desired Locale for the query results
 *
 * @throws NullPointerException if Locale is null
 */
private val geocoder: Geocoder = Geocoder(context, Locale.getDefault())

/**
 * A variable of address listener interface.
 */
private lateinit var mAddressListener: AddressListener

/**
 * Background method of AsyncTask where the background operation will be performed.
 */
@Deprecated("Deprecated in Java")
override fun doInBackground(vararg params: Void?): String {
    try {
        /**
         * Returns an array of Addresses that are known to describe the
         * area immediately surrounding the given latitude and longitude.
         */
        val addressList: List<Address>? = geocoder.getFromLocation(latitude, longitude, 1)

        if (addressList != null && addressList.isNotEmpty()) {
            val address: Address = addressList[0]
            val sb = StringBuilder()
            for (i in 0..address.maxAddressLineIndex) {
                sb.append(address.getAddressLine(i)).append(",")
            }
            sb.deleteCharAt(sb.length - 1) // Here we remove the last comma that we have added above from the address.
            return sb.toString()
        }
    } catch (e: IOException) {
        Log.e("HappyPlaces", "Unable connect to Geocoder")
    }

    return ""
}

/**
 * onPostExecute method of AsyncTask where the result will be received and assigned to the interface accordingly.
 */
@Deprecated("Deprecated in Java")
override fun onPostExecute(resultString: String?) {
    if (resultString == null) {
        mAddressListener.onError()
    } else {
        mAddressListener.onAddressFound(resultString)
    }
    super.onPostExecute(resultString)
}

/**
 * A public function to set the AddressListener.
 */
fun setAddressListener(addressListener: AddressListener) {
    mAddressListener = addressListener
}

/**
 * A public function to execute the AsyncTask from the class is it called.
 */
fun getAddress() {
    execute()
}

/**
 * A interface for AddressListener which contains the function like success and error.
 */
interface AddressListener {
    fun onAddressFound(address: String?)
    fun one rror()
}

}

CodePudding user response:

You can use Handler instead.

class GetAddrFromLatLog(
    context: Context,
    private val latitude: Double,
    private val longitude: Double
) : Runnable {

    private val geocoder: Geocoder = Geocoder(context, Locale.getDefault())

    var addressListener: AddressListener? = null
        private get

    override fun run() {
        try {
            val addressList = geocoder.getFromLocation(latitude, longitude, 1)

            if (addressList != null || addressList.isNotEmpty()) {
                val address: Address = addressList[0]
                val sb = StringBuilder()
                for (i in 0..address.maxAddressLineIndex) {
                    sb.append(address.getAddressLine(i)).append(",")
                }
                sb.deleteCharAt(sb.length - 1) // Here we remove the last comma that we have added above from the address.
                addressListener?.onAddressFound(sb.toString())
            } else {
                addressListener?.onError()
            }
        } catch (e: IOException) {
            Log.e("HappyPlaces", "Unable connect to Geocoder")
            addressListener?.onError()
        }
    }

    interface AddressListener {
        fun onAddressFound(address: String?)
        fun one rror()
    }
}

// You functionto call `GetAddrFromLatLog` class
fun getGeoAddress(callback: AddressListener?) {
    val th = HandlerThread("getAddr")
    th.start()
    
    val handler = Handler(th.getLooper())
    handler.post(GetAddrFromLatLog(context, lat, log).apply {
        addressListener = callback
    })
}

CodePudding user response:

I think you can use RxJava to replace AsyncTask as well

  • Related