Reputation: 4807
The value of the key "KEY_PHOTO"
in each HashMap
holds an url to an image that I need to put inside R.id.imageView
, how can I convert url to Bitmap
?
public class MainActivity extends Activity {
private static final String TAG = "TAG";
ArrayList<HashMap<String, String>> usersHashMap;
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usersHashMap = new ArrayList<HashMap<String, String>>();
listView = (ListView) findViewById(R.id.listView1);
new readJson().execute();
}
class readJson extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... arg) {
JSONParser jParser = new JSONParser();
JSONObject json = null;
json = jParser.getJSONFromUrl("link");
try {
JSONArray users = json.getJSONArray("users");
for (int i = 0; i < users.length(); i++) {
JSONObject obj = users.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put("KEY_NAME", obj.getString("name"));
map.put("KEY_PHOTO", obj.getString("photo"));
map.put("KEY_AGE", obj.getString("age"));
usersHashMap.add(map);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d(TAG, ""+json);
return null;
}
@Override
protected void onPostExecute(String result) {
SimpleAdapter adapter = new SimpleAdapter(getApplicationContext(), usersHashMap, R.layout.list_view,
new String[] { "KEY_NAME", "KEY_AGE", "KEY_PHOTO" },
new int[] { R.id.list_headline,R.id.list_info,R.id.imageView }); //set photo url to R.id.imageView
listView.setAdapter(adapter);
super.onPostExecute(result);
}
}
}
Upvotes: 1
Views: 1482
Reputation: 3078
Extract the value from the HashMap
with the key of"KEY_PHOTO"
. Then, apply the mapping below to the value to get back a Bitmap
.
You can convert a string url to a Bitmap
object with the code snippet below:
URL url = new URL(INSERT_STRING_URL_HERE);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoInput(true);
con.connect();
InputStream input = con.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
Be sure to replace INSERT_STRING_URL_HERE
with a string of the url.
Upvotes: 1