【问题标题】:AsyncTask takes forever to fetch resultAsyncTask 需要永远获取结果
【发布时间】:2019-11-01 03:06:27
【问题描述】:

我正在制作一个需要从在线数据库中获取数据的 android 应用程序。在线数据库有 3 列,日期、时间和 Varchar(255)

这是我的 PHP 代码:

<?php
require "connection.php";
if($result = mysqli_query($conn, "select * from `xuberance_updates`")) {
while($row = mysqli_fetch_assoc($result)) {
    echo $row["date"].",".$row["time"].",".$row["updates"].";";
}
}
?>

这是我在 android 中的 kotlin 代码:

class RefreshTask(private val alertDialog: AlertDialog) :
    AsyncTask<String, Void, String>() {

    override fun onPreExecute() {
        ...
        alertDialog.show()
        ...
    }

    override fun doInBackground(vararg params: String?): String? {
        val url = URL("https://.../show_update.php")
        val httpURLConnection = url.openConnection() as HttpURLConnection
        httpURLConnection.doInput = true
        httpURLConnection.doOutput = true
        httpURLConnection.requestMethod = "POST"
        httpURLConnection.connect()
        val reader = BufferedReader(InputStreamReader(httpURLConnection.inputStream, "UTF-8"))
        var line = reader.readLine()
        val result = StringBuilder()
        while (line != null) {
            result.append(line)
            line = reader.readLine()
        }
        reader.close()
        httpURLConnection.disconnect()
        return result.toString()
    }

    override fun onPostExecute(result: String?) {
        alertDialog.dismiss()
        ...
    }
    ...
}

当我启动 AsyncTask 时,会出现对话框。但它永远不会被解雇。 onPostExecute(result: String?) 方法永远不会到达。如何解决这个问题?

编辑:有时,它成功到达 onPostExecute(result: String?) 方法。但大多数时候,我需要等待 2 分钟或更长时间才能使用该方法。

【问题讨论】:

  • 可能是因为你得到的数据太大
  • 目前数据库为空。即便如此,我的问题仍然存在。我尝试使用我的 Wifi 和移动数据(非常快),但没有结果。

标签: php android kotlin android-asynctask


【解决方案1】:

使用此库进行网络调用。非常简单而高效。 http://loopj.com/android-async-http/

【讨论】:

    【解决方案2】:

    这应该是罪魁祸首

     while (line != null) {
                result.append(line)
                line = reader.readLine()
            }
    

    【讨论】:

    • 我已尝试删除该行。我的问题仍然存在
    • 删除后执行中的空安全检查......可能这就是为什么不调用后执行
    • 执行后方法没有空安全检查。 null 安全检查将如何影响dismiss() 方法的调用?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-08
    • 2012-10-14
    • 1970-01-01
    • 1970-01-01
    • 2021-03-17
    • 2014-02-24
    • 2014-07-08
    相关资源
    最近更新 更多