IOException:AsyncTask图像下载Kotlin Android(坏文件描述符)

时间:2017-11-09 13:45:58

标签: android android-asynctask kotlin

更新

经过一些调试后,我发现了这一点 在没有任何异常异常的情况下执行给定代码中的Catch块。 我打印输入流返回一些值,事件位图varibale初始化,但一旦执行了catch块,它返回null到onPostExecute方法。

找出它为什么会发生?

Please check debug screenshot of studio

END

我正在使用Android Studio 3.0。

使用Kotlin支持创建简单的Android应用程序,在AsyncTask类和HTTPURLConnection类的帮助下从http协议URL下载图像。

在执行AsyncTask类时,我从HTTPURLConnection对象获取http响应代码200,但在使用BitmapFactory.decodeStream(inputstream)方法解码流时抛出IOEXception。

StackTrace倾向于错误引起:android.system.ErrnoException:recvfrom failed:EBADF,在调用此BitmapFactory.decodeStream(inputstream)方法的同一行上。

    override fun doInBackground(vararg args: String?): Bitmap? {

    var bitmap: Bitmap? = null

    try {

        val url = URL(args[0])
        val connection: HttpURLConnection = url.openConnection() as HttpURLConnection

        connection.requestMethod = "GET"
        connection.connectTimeout = 10 * 60 * 60
        connection.readTimeout = 10 * 60 * 60
        connection.doInput = true
        connection.doOutput = true

        connection.connect()
        val responseCode = connection.responseCode
        if (HTTP_OK == responseCode) {
            if (null != connection.inputStream) {
                val inputStream = connection.inputStream
                connection.disconnect()
                bitmap = BitmapFactory.decodeStream(inputStream)
            }
        }else{
            Log.e("####","Error Response Code: ${responseCode}")
        }

    } catch (ex: IOException) {
        Log.e("####",ex.localizedMessage)

    } catch (ex: MalformedURLException) {
        ex.printStackTrace()

    } catch (ex: Exception) {
        ex.printStackTrace()

    }

    return bitmap
}

2 个答案:

答案 0 :(得分:1)

您只能在之后调用disconnect ,您已经阅读了回复正文。

答案 1 :(得分:1)

这是java,但你可以将它改编为Kotlin:

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
connection.disconnect()