[英]Android get image from server to SQLite database
Android将图像从服务器获取到SQLite数据库
我需要在新闻部分显示图像,并且当没有互联网连接时,我想离线阅读它们。 我是用标题和正文来完成的,但是对于新闻图像来说太慢了,我该如何改善呢?
我试图获取字符串url并将其存储为字节数组:
public byte[] downloadImage(String urlImg) throws Exception{
URL url = new URL(urlImg);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setReadTimeout(10000);
con.setConnectTimeout(10000);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
Bitmap b = BitmapFactory.decodeStream(con.getInputStream());
b.compress(Bitmap.CompressFormat.WEBP, 0, bos);
} finally {
con.disconnect();
}
return bos.toByteArray();
}
然后我在doInBackground内部这样称呼它:
@Override
protected Boolean doInBackground(String... urls) {
try {
HttpGet httppost = new HttpGet("http://www.77-webdev.com/clients/thebeautyworkshop/news.json");
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
int status = response.getStatusLine().getStatusCode();
if (status == 200){
DataSource.deleteAll();
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsonObject = new JSONObject(data);
JSONArray jsonArray = jsonObject.getJSONArray("News");
News news = new News();
for (int i=0; i < jsonArray.length();i++){
JSONObject JObject = jsonArray.getJSONObject(i);
String Title = JObject.getString("title");
String body = JObject.getString("mobile_body");
String Image = JObject.getString("image");
String lang = JObject.getString("lang");
byte[] IMG = downloadImage(Image);
news.setTitle(Title);
news.setMobile_body(body);
news.setImageB(IMG);
news.setLang(lang);
DataSource.create(news);
newsList.add(news);
}
return true;
}
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
但这也是因为我要为每个图像进行连接
如果知道要将图像放入哪个视图,则可以使用Square的Picasso简化图像处理:
Picasso
.with(context)
.load(Image)
.into(imageView);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.