我的最后一年项目要求我开发一个移动应用程序,它从服务器获取许多Json值。这是我在Android开发方面的第一次经历,但确实学到了一些东西,并享受了这种体验。
我设法开发了以下内容。
1 - 一个获取值的json解析器类。
2 - 显示这些值的类。
3 - 我存储json响应的数据库。
然而,我离完成项目只有一步之遥,我无法将响应字符串图像地址显示为真实图像(对我来说很遗憾)。 我需要做以下事情。
1-解析图像的字符串路径并将响应显示为图像。
我花了大部分时间试图在网上找到解决方案,堆栈溢出。但到目前为止没有运气。 我需要执行this之类的操作才能将这些图像与文本说明一起显示。
我现在已经到了十字路口,我的知识已经过测试。我想在这里做什么才能做到?
谁能指路我? ,到这个优秀的平台。
答案 0 :(得分:1)
如果您将图像url
作为字符串,则可以使用以下内容加载和保存图像:
try {
Bitmap bitmap = null;
File f = new File(filename);
InputStream inputStream = new URL(url).openStream();
OutputStream outputStream = new FileOutputStream(f);
int readlen;
byte[] buf = new byte[1024];
while ((readlen = inputStream.read(buf)) > 0)
outputStream.write(buf, 0, readlen);
outputStream.close();
inputStream.close();
bitmap = BitmapFactory.decodeFile(filename);
return bitmap;
} catch (Exception e) {
return null;
}
如需保存,请确保您具有适当的权限,如果您要保存到SD卡。
如果您只想加载图片(不保存):
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e(TAG, "Error getting bitmap", e);
}
return bm;
只需确保您在单独的帖子中获取图片或使用AsyncTask
,否则您将获得ANR!
答案 1 :(得分:1)
你可以从谷歌尝试这个ImageDownloader类。它很好用:) 是一个处理下载并将位图设置为ImageView的AsynkTask。
用法:
private final ImageDownloader mDownload = new ImageDownloader();
mDownload.download("URL", imageView);