问题
I'm doing my BlogApp. It gets all data from the Internet. I added three TextViews, but I have problem with getting images from JSON. I've tryed different ways but I still don't understand how exactly do this. Here is a part of my code:
private void handleBlogResponse() {
mProgressBar.setVisibility(View.INVISIBLE);
if (mBlogData==null){
updateDisplayForError();
}else {
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
ArrayList<HashMap<String, String>> blogPosts = new ArrayList<HashMap<String, String>>();
for (int i=0; i<jsonPosts.length(); i++){
JSONObject posts = jsonPosts.getJSONObject(i);
String title = posts.getString(KEY_TITLE); //"title"
title = Html.fromHtml(title).toString();
String author = posts.getString(KEY_AUTHOR); //"author"
author = Html.fromHtml(author).toString();
String time = posts.getString((KEY_TIME)); //"time"
time = Html.fromHtml(time).toString();
String icon = posts.getString(KEY_ICON); //"icon" (icons url)
icon = Html.fromHtml(icon).toString();
I stoped here, and don't know what to do next! Probably I should add an Adapter for my Images to convert it?
HashMap<String, String> blogPost = new HashMap<String, String>();
blogPost.put(KEY_TITLE, title);
blogPost.put(KEY_AUTHOR, author);
blogPost.put(KEY_TIME, time);
blogPosts.add(blogPost);
}
String[] keys = {KEY_TITLE, KEY_AUTHOR, KEY_TIME};
int[] ids = {R.id.textView1, R.id.textView2, R.id.textView3};
SimpleAdapter adapter = new SimpleAdapter(this, blogPosts, R.layout.row_layout,
keys, ids);
setListAdapter(adapter);
} catch (JSONException e) {
Log.e(TAG, "Exception caught" + e);
}
}
}
Thanks for waching this!
回答1:
Volley Library makes this work quite easy and handles all other related tasks itself. You can use ImageLoader or NetworkImageView.
Follow the link for how to acheive it: https://developer.android.com/training/volley/request.html
回答2:
First of all download image from url then set it into your imageView.
public class LoadImageFromURL extends AsyncTask{
@Override
protected Bitmap doInBackground(String... params) {
try {
URL url = new URL("image-url");
InputStream is = url.openConnection().getInputStream();
Bitmap bitMap = BitmapFactory.decodeStream(is);
return bitMap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
yourImageview.setImageBitmap(result);
}
}
I Hope it will help you..!
来源:https://stackoverflow.com/questions/30453679/how-to-get-images-from-internet-and-past-it-in-a-listview