猿问

AsyncTask 需要永远获取结果

我正在制作一个 android 应用程序,我需要从在线数据库中获取数据。在线数据库有 3 列,Date, Time 和 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(结果:字符串)方法从未达到。如何解决这个问题?


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


蓝山帝景
浏览 128回答 2
2回答

料青山看我应如是

这应该是罪魁祸首&nbsp;while (line != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result.append(line)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; line = reader.readLine()&nbsp; &nbsp; &nbsp; &nbsp; }
随时随地看视频慕课网APP
我要回答