首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Kotlin显示来自AsyncTask的Toast消息

使用Kotlin显示来自AsyncTask的Toast消息
EN

Stack Overflow用户
提问于 2020-07-31 18:35:33
回答 1查看 592关注 0票数 0

关于这个话题,已经有很多答案了,但我无法开始工作。

从其中一个活动中,我调用我的异步任务如下:

代码语言:javascript
复制
DownloadChapters().execute(currentChapUrl)

我的异步任务如下所示:

代码语言:javascript
复制
   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()
    
        }
    
    }

错误显示在吐司函数上。

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-31 18:41:37

在实例化Context并在onPostExecute中使用它时,将它的实例传递给DownloadChapters。确保这是一个applicationContext,以避免意外泄漏您的活动。

代码语言:javascript
复制
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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63197350

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档