每个"KEY_PHOTO"
中的密钥HashMap
的值包含我需要放入R.id.imageView
内的图片的网址,如何将网址转换为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);
}
}
}
答案 0 :(得分:1)
使用HashMap
键从"KEY_PHOTO"
中提取值。然后,将下面的映射应用于该值以返回Bitmap
。
您可以使用下面的代码段将字符串网址转换为Bitmap
对象:
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);
请务必使用网址字符串替换INSERT_STRING_URL_HERE
。