【问题标题】:Showing a Toast message from AsyncTask using Kotlin使用 Kotlin 显示来自 AsyncTask 的 Toast 消息
【发布时间】:2020-11-21 15:01:33
【问题描述】:

已经有很多关于这个主题的答案,但我无法让我的工作。

从其中一项活动中,我这样调用我的 asynctask:

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()
    
        }
    
    }

错误显示在 toast 函数中。

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作为makeText函数的第一个参数。你正在传递this,这是你的AsyncTask。顺便说一句,AsyncTask 已弃用。

标签: android kotlin android-asynctask android-context


【解决方案1】:

当您实例化它并在onPostExecute 中使用它时,将Context 的实例传递给DownloadChapters。确保它是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 替换为 Coroutines。 AsyncTask is deprecated.

【讨论】:

  • 我最近几周才开始学习这个。我不确定如何将 Context 传递给 DownloadChapters。现在使用最流行的方法(如 AsyncTask)来学习,然后再使用最新的方法。
  • 我已经用代码 sn-p 更新了我的答案。没有理由再学习 AsyncTasks,这是一种过时的技术,不应该在新编写的代码中使用。 AsyncTask 存在重大缺陷,使用起来很危险。
  • 我同意 @Egor 协程使线程更容易
  • 谢谢。完美工作。我也会研究协程。
  • 哇。我用协程替换了 asynctask。切换上下文非常简单且非常容易。伟大的。非常感谢您的推荐。 _/_
猜你喜欢
  • 1970-01-01
  • 2014-05-06
  • 2015-02-12
  • 2014-05-23
  • 2019-04-28
  • 2011-12-09
  • 2014-07-04
  • 1970-01-01
相关资源
最近更新 更多