Issue
There are many answers on this topic already, but I am not able to get mine working.
From one of the activities, I am calling my asynctask like this:
DownloadChapters().execute(currentChapUrl)
My asynctask looks like this:
class DownloadChapters() : AsyncTask<String, Void, String>() {
override fun doInBackground(vararg startingChapUrl : String): String? {
//processing.. downloading from url's etc..
val result = "A total of $chapCount chapters Downloaded"
return result //I want to show this "result" as a toast message.
}
//trying to showing toast message here, but I cant get the context right, is what I am guessing. Please help.
override fun onPostExecute(result: String) {
super.onPostExecute(result)
Toast.makeText(this, result , Toast.LENGTH_SHORT).show()
}
}
The error shows at the toast function.
None of the following functions can be called with the arguments supplied:
public open fun makeText(p0: Context!, p1: CharSequence!, p2: Int): Toast! defined in android.widget.Toast
public open fun makeText(p0: Context!, p1: Int, p2: Int): Toast! defined in android.widget.Toast
Solution
Pass an instance of Context to DownloadChapters when you instantiate it and use it in onPostExecute. Make sure it's an applicationContext, to avoid accidentally leaking your Activity.
class DownloadChapters(private val context: Context) : AsyncTask<String, Void, String>() {
override fun onPostExecute(result: String) {
super.onPostExecute(result)
Toast.makeText(context, result , Toast.LENGTH_SHORT).show()
}
}
// In Activity
DownloadChapters(applicationContext).execute(currentChapUrl)
Better yet, replace your AsyncTask with Coroutines. AsyncTask is deprecated.
Answered By - Egor
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.