使用 Kotlin 显示来自 AsyncTask 的 Toast 消息
Showing a Toast message from AsyncTask using Kotlin
已经有很多关于这个主题的答案,但我无法让我的工作。
在其中一项活动中,我这样调用我的异步任务:
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
实例化时将 Context
的实例传递给 DownloadChapters
并在 onPostExecute
中使用它。确保它是 applicationContext
,以避免意外泄露你的 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)
更好的是,用协程替换 AsyncTask。 AsyncTask is deprecated.
已经有很多关于这个主题的答案,但我无法让我的工作。
在其中一项活动中,我这样调用我的异步任务:
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
实例化时将 Context
的实例传递给 DownloadChapters
并在 onPostExecute
中使用它。确保它是 applicationContext
,以避免意外泄露你的 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)
更好的是,用协程替换 AsyncTask。 AsyncTask is deprecated.