0

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)

}
}
mjuarez
  • 16,372
  • 11
  • 56
  • 73
  • Does this answer your question? [How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?](https://stackoverflow.com/questions/12575068/how-to-get-the-result-of-onpostexecute-to-main-activity-because-asynctask-is-a) – mightyWOZ Jan 11 '20 at 17:31
  • It doesn't answer my qauestion – user6070761 Jan 11 '20 at 18:15
  • It answered my question after all but I decided to use coroutines – user6070761 Jan 13 '20 at 19:35

2 Answers2

1

You can call the get() method of AsyncTask (or the overloaded get(long, TimeUnit)). This method will block until the AsyncTask has completed its work, at which point it will return you the Result.

It would be wise to be doing other work between the creation/start of your async task and calling the get method, otherwise, you aren't utilizing the async task very efficiently.

Ravi
  • 2,277
  • 3
  • 22
  • 37
0

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.

Timotej Leginus
  • 304
  • 3
  • 18