Android在listview中显示来自url的图像

时间:2015-03-23 15:55:59

标签: android image listview imageview

我想在我的应用程序中显示图像,我从mysql数据库中获取这些图像的URL。目前它只显示图像的URL作为文本

如何下​​载图像并在列表视图中显示?

 /**
 * Retrieves recent post data from the server.
 */
public void updateJSONdata() {

    // Instantiate the arraylist to contain all the JSON data.
    // we are going to use a bunch of key-value pairs, referring
    // to the json element name, and the content, for example,
    // message it the tag, and "I'm awesome" as the content..

    mCommentList = new ArrayList<HashMap<String, String>>();

    // Bro, it's time to power up the J parser
    JSONParser jParser = new JSONParser();
    // Feed the beast our comments url, and it spits us
    //back a JSON object.  Boo-yeah Jerome.
    JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);

    //when parsing JSON stuff, we should probably
    //try to catch any exceptions:
    try {

        //I know I said we would check if "Posts were Avail." (success==1)
        //before we tried to read the individual posts, but I lied...
        //mComments will tell us how many "posts" or comments are
        //available
        mComments = json.getJSONArray(TAG_POSTS);

        // looping through all posts according to the json object returned
        for (int i = 0; i < mComments.length(); i++) {
            JSONObject c = mComments.getJSONObject(i);

            //gets the content of each tag
            String title = c.getString(TAG_TITLE);
            String content = c.getString(TAG_MESSAGE);
            String username = c.getString(TAG_USERNAME);
            String url = c.getString(TAG_URL);




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

            map.put(TAG_TITLE, title);
            map.put(TAG_MESSAGE, content);
            map.put(TAG_USERNAME, username);
            map.put(TAG_URL, url);

            // adding HashList to ArrayList
            mCommentList.add(map);

            //annndddd, our JSON data is up to date same with our array list
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
}



/**
 * Inserts the parsed data into the listview.
 */
private void updateList() {
    // For a ListActivity we need to set the List Adapter, and in order to do
    //that, we need to create a ListAdapter.  This SimpleAdapter,
    //will utilize our updated Hashmapped ArrayList,
    //use our single_post xml template for each item in our list,
    //and place the appropriate info from the list to the
    //correct GUI id.  Order is important here.
    ListAdapter adapter = new SimpleAdapter(this, mCommentList,
            R.layout.single_post, new String[] { TAG_TITLE, TAG_MESSAGE,
            TAG_USERNAME, TAG_URL }, new int[] { R.id.title, R.id.message,
            R.id.username, R.id.url });

    // I shouldn't have to comment on this one:
    setListAdapter(adapter);

    // Optional: when the user clicks a list item we
    //could do something.  However, we will choose
    //to do nothing...
    ListView lv = getListView();
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {

            // This method is triggered if an item is click within our
            // list. For our example we won't be using this, but
            // it is useful to know in real life applications.

        }
    });

编辑:JSONParser.java

 package com.test.mysqltest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }


    public JSONObject getJSONFromUrl(final String url) {

        // Making HTTP request
        try {
            // Construct the client and the HTTP request.
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            // Execute the POST request and store the response locally.
            HttpResponse httpResponse = httpClient.execute(httpPost);
            // Extract data from the response.
            HttpEntity httpEntity = httpResponse.getEntity();
            // Open an inputStream with the data content.
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            // Create a BufferedReader to parse through the inputStream.
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            // Declare a string builder to help with the parsing.
            StringBuilder sb = new StringBuilder();
            // Declare a string to store the JSON object data in string form.
            String line = null;

            // Build the string until null.
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            // Close the input stream.
            is.close();
            // Convert the string builder data to an actual string.
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // Try to parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // Return the JSON Object.
        return jObj;

    }


    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
                                      List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

3 个答案:

答案 0 :(得分:1)

请看这篇文章http://www.androidhive.info/2014/07/android-custom-listview-with-image-and-text-using-volley/

这是使用Volley库获取和显示图像的示例。

问题出在你的ListAdapter中。 SimpleAdapter只是将字段显示为字符串。

使用自定义视图实现您自己的适配器。

答案 1 :(得分:0)

为简单起见,您可以这样做: 当你得到一个图像的网址。只需拍摄一张imageView。例如:

ImageView logo = (ImageView) rootView.findViewById(R.id.logo);

这些代码块可能有效:

   try {
            // Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(" http://corporate2.bdjobs.com/21329.jpg").getContent());
            Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(m.getLogo()).getContent());
            //  http://corporate2.bdjobs.com/21329.jpg
            logo.setImageBitmap(bitmap);
            //convertView.setBackgroundResource(R.drawable.cardlayout);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

如果您想要更深入并通过队列管理让应用程序更好地运行,那么您可以尝试this tutorial

答案 2 :(得分:0)

这是将帖子内容添加到列表视图的困难部分:

            //gets the content of each tag
            String title = c.getString(TAG_TITLE);
            String content = c.getString(TAG_MESSAGE);
            String username = c.getString(TAG_USERNAME);
            String url = c.getString(TAG_URL);  // <- Gets Image Url





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

            map.put(TAG_TITLE, title);
            map.put(TAG_MESSAGE, content);
            map.put(TAG_USERNAME, username);
            map.put(TAG_URL, url);         //<- Adds Image Url as text to post

            // adding HashList to ArrayList
            mCommentList.add(map);

输出: Screenshot