关于这个话题,已经有很多答案了,但我无法开始工作。
从其中一个活动中,我调用我的异步任务如下:
DownloadChapters().execute(currentChapUrl)我的异步任务如下所示:
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()
}
}错误显示在吐司函数上。
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发布于 2020-07-31 18:41:37
在实例化Context并在onPostExecute中使用它时,将它的实例传递给DownloadChapters。确保这是一个applicationContext,以避免意外泄漏您的活动。
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)更好的方法是,将AsyncTask替换为Coroutines。不建议使用AsyncTask。
https://stackoverflow.com/questions/63197350
复制相似问题