【发布时间】:2020-02-05 14:50:38
【问题描述】:
我从 API 接收图像和其他数据的 URL 并将图像显示到 recyclerview,我想以字节数组格式将图像存储在房间数据库中,但是在将图像 URL 转换为字节数组时出现错误.我的应用程序在 url.openstream(); 处崩溃。
private byte[] getByteArrayImage(String imageUrl) {
URL url = null;
try {
url = new URL(imageUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
byte[] chunk = new byte[4096];
int bytesRead;
InputStream stream = url.openStream();
while ((bytesRead = stream.read(chunk)) > 0) {
outputStream.write(chunk, 0, bytesRead);
}
url.openStream().close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
return outputStream.toByteArray();
}
【问题讨论】:
-
你调用 openStream() 两次。
标签: java android api android-room