androidkotlin

How to get a value from Kotlin AsyncTask


I can't get one solution for this. I have searched many things and I can't get an answer. Please help me. This is my code

class NewTask : AsyncTask<Void, Void, String>() {
public override fun doInBackground(vararg params: Void?): String? {
    val arr = ArrayList<String>()
    val url = URL("http://boogle.org")

    with(url.openConnection() as HttpURLConnection) {
        requestMethod = "GET"  // optional default is GET

        //arr.add(responseCode)

        inputStream.bufferedReader().use {
            it.lines().forEach { line ->
                //println(line)
                arr.add(line as String)
            }
        }
    }
    return arr.get(0)
}

public override fun onPostExecute(result: String?) {
    //super.onPostExecute(result)

}
}

Solution

  • I had the same problem, but I settled on coroutines. Here is the code I used:

    class CoRoutine{
    suspend fun httpGet(url: String = "https://boogle.org"): String {
    val arr = ArrayList<String>()
    withContext(Dispatchers.IO) {
        val url = URL(url)
    
        with(url.openConnection() as HttpURLConnection) {
            requestMethod = "GET"  // optional default is GET
    
            //arr.add(responseCode)
    
            inputStream.bufferedReader().use {
                it.lines().forEach { line ->
                    //println(line)
                    arr.add(line as String)
                }
            }
        }
    }
    return arr.get(0)
    }
    }
    

    Answer taken from my other answer.