如何动态地从json在listview中显示图像

时间:2013-05-08 22:54:55

标签: android json android-listview android-arrayadapter

我想列出json中的文字和图片,特别是url

我已连续显示textview但如何显示图像我的代码是

public class AndroidJSONParsingActivity extends ListActivity {


    // url to make request
    private static String url = "***MY URL***";

    // JSON Node names

    private static final String TAG_ID = "id";
    private static final String TAG_NAME = "name";
    private static final String TAG_PRICE = "price";
    private static final String TAG_URL = "hosting_thumbnail_url";


    // contacts JSONArray


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_android_jsonparsing);

        // Hashmap for ListView
        ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();

        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        // getting JSON string from URL
        JSONArray json = jParser.getJSONFromUrl(url);

        try {
            // Getting Array of Contacts


            // looping through All Contacts
            for(int i = 0; i < json.length(); i++){
                JSONObject c = json.getJSONObject(i);

                // Storing each json item in variable
                String id = c.getString(TAG_ID);
                String name = c.getString(TAG_NAME);
                String email = c.getString(TAG_PRICE);
                //String  image1 = c.getString( TAG_URL);

                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                map.put(TAG_ID, id);
                map.put(TAG_NAME, name);
                map.put(TAG_PRICE, email);
                //map.put(TAG_URL, image1);


                // adding HashList to ArrayList
                contactList.add(map);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(this, contactList,
                R.layout.list_item,
                new String[] { TAG_NAME, TAG_PRICE }, new int[] {
                        R.id.name, R.id.email });

        setListAdapter(adapter);


    }

}

我希望listview像这样“http://pic002.cnblogs.com/images/2012/372551/2012021011374176.jpg

2 个答案:

答案 0 :(得分:2)

您需要编写自定义列表适配器。谷歌为“android自定义listadapter图像”。第一个打击是this一个,看起来像一个不错的例子。

答案 1 :(得分:0)

正如SimonSays所说,你必须实现自己的ListView适配器类及其getView()方法。

如果您计划在ListView中动态获取这些JSON对象,我强烈建议使用一些Thread机制,该机制会在获得时立即将该JSON对象的数据设置为ListView - 即AsyncTask