Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/assembly/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在android中下载图片_Android_Android Layout_Android Intent - Fatal编程技术网

在android中下载图片

在android中下载图片,android,android-layout,android-intent,Android,Android Layout,Android Intent,亲爱的所有人,我正在使用下面的代码在android中下载图片, 其中_in作为输入流,DataInputStream _din。 我使用一个URL下载图片。但有时它返回图片,有时它在位图中不显示空。我这里有一个问题,一个是下载图片的好方法,或者建议图片中可能有什么错误,相同的代码有时返回图片,有时不起作用 if (_in == null) { _in = urlConnection.getInputStream(); } if (_din == null) {

亲爱的所有人,我正在使用下面的代码在android中下载图片, 其中_in作为输入流,DataInputStream _din。 我使用一个URL下载图片。但有时它返回图片,有时它在位图中不显示空。我这里有一个问题,一个是下载图片的好方法,或者建议图片中可能有什么错误,相同的代码有时返回图片,有时不起作用

if (_in == null) {
        _in = urlConnection.getInputStream();
    }
    if (_din == null) {
        _din = new DataInputStream(_in);
    }

    byte[] data = new byte[0];
    byte[] buffer = new byte[512];
    int bytesRead;
    while ((bytesRead = _din.read(buffer)) > 0) {           
        byte[] newData = new byte[data.length + bytesRead];         
        System.arraycopy(data, 0, newData, 0, data.length);         
        System.arraycopy(buffer, 0, newData, data.length, bytesRead);           
        data = newData;
    }       
    InputStream is = new ByteArrayInputStream(data);
    Bitmap bmp = BitmapFactory.decodeStream(is);

试试这个,告诉我你的问题是否仍然存在

Bitmap ret;
        HttpURLConnection conn = null;          
        try
        {
            URL u = new URL(mUrl);
            conn = (HttpURLConnection) u.openConnection();
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setReadTimeout(CONNECTION_TIMEOUT);
            conn.setDoInput(true);
            conn.setRequestMethod("GET");

            int httpCode = conn.getResponseCode();
            if (httpCode == HttpURLConnection.HTTP_OK || httpCode == HttpURLConnection.HTTP_CREATED)
            {
                InputStream is = new BufferedInputStream(conn.getInputStream());
                ret = BitmapFactory.decodeStream(is);
            }
            else
            {
                ret = null;
            }
        }
        catch (Exception ex)
        {
            ret = null;
        }
        finally
        {
            if (conn != null)
            {
                conn.disconnect();
            }
        }

为什么对图像输入流使用临时缓冲区?只需将UrlConnection InputStream直接用于BitmapFactory:

_in = urlConnection.getInputStream();
Bitmap bmp = BitmapFactory.decodeStream(_in);

如果您的图像正常,这应该始终有效。

您好,提示。我做到了。做更多的测试,使其符合要求。