Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.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 - Fatal编程技术网

为什么这个图像位图没有在Android中下载?

为什么这个图像位图没有在Android中下载?,android,Android,我有一个应用程序,其中我必须从URL下载一个图像。我使用以下代码进行相同的操作: URL url = new URL(address); URLConnection conn = url.openConnection(); conn.connect(); int length = conn.getContentLength(); is = conn.getInputStream(); bis = new BufferedInputStream(is, length); bm = BitmapFa

我有一个应用程序,其中我必须从URL下载一个图像。我使用以下代码进行相同的操作:

URL url = new URL(address);
URLConnection conn = url.openConnection();
conn.connect();
int length = conn.getContentLength();
is = conn.getInputStream();
bis = new BufferedInputStream(is, length);
bm = BitmapFactory.decodeStream(bis);

由于某种原因返回的bm的高度和宽度为-1,这是一个非法状态异常。高度和宽度为-1的原因可能是什么?

您应该检查长度字段返回的内容。如果下载失败,大多数类型的方法都会返回-1作为内容长度

请查看下面的代码

String url = server url;
InputStream ins = null;
    try {
        ins = new java.net.URL(url).openStream();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

Bitmap b = BitmapFactory.decodeStream(new FlushedInputStream(ins));
imageview.setImageBitmap(b);
并在函数下面使用

 static class FlushedInputStream extends FilterInputStream {
    public FlushedInputStream(InputStream inputStream) {
        super(inputStream);
    }

    @Override
    public long skip(long n) throws IOException {
        long totalBytesSkipped = 0L;
        while (totalBytesSkipped < n) {
            long bytesSkipped = in.skip(n - totalBytesSkipped);
            if (bytesSkipped == 0L) {
                int b = read();
                if (b < 0) {
                    break; // we reached EOF
                } else {
                    bytesSkipped = 1; // we read one byte
                }
            }
            totalBytesSkipped += bytesSkipped;
        }
        return totalBytesSkipped;
    }
}
静态类FlushedInputStream扩展FilterInputStream{
公共FlushedInputStream(InputStream InputStream){
超级(输入流);
}
@凌驾
公共长跳过(长n)引发IOException{
长的总重量=0升;
while(totalBytesSkipped
conn.length()返回16333字节src name在这里指的是什么。我能放什么吗?文档对此不清楚…请检查链接感谢您的回复,但您提供的代码不起作用。有时,drawable从源代码返回空值,有时甚至在我通过setImageDrawable()设置它时返回空值。。正在引发异常。请检查答案我已更新它,我认为它对您更有帮助。如果有任何疑问,请告诉我。若你们觉得这是有帮助的,那个么正确的回答并投票,这样对其他人也会有更多的帮助。