如何在listview中显示位图?

时间:2014-08-20 19:47:09

标签: android android-listview android-bitmap

我想在ListView中显示已下载的图片。使用函数DownloadImage下载图像并使用位图。

如何在ListView

中显示此内容

存储在xampp中的文件夹htdocs中的图像和表格书中带有book_id的名称图像相等(book_id = 100和name image = 100.png)。我希望每本书都有自己的图像。

我可以在ListView book_namebook_price中展示。问题出在图像书上。

类:

    package bookstore.category;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.squareup.picasso.Picasso;

import android.R.drawable;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import bookstore.pack.JSONParser;
import bookstore.pack.R;

import android.app.Activity;
import android.app.ProgressDialog;

public class Computer extends Activity {
//Bitmap bm = null;
// progress dialog
private ProgressDialog pDialog;

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

ArrayList<HashMap<String, String>> computerBookList;

private static String url_books = "http://10.0.2.2/project/computer.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_BOOK = "book";
private static final String TAG_BOOK_NAME = "book_name";
private static final String TAG_BOOK_PRICE = "book_price";
private static final String TAG_BOOK_ID = "book_id";
private static final String TAG_MESSAGE = "massage";

// category JSONArray
JSONArray book = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.category);
    Typeface font1 = Typeface.createFromAsset(getAssets(),
            "font/bnazanin.TTF");
    // Hashmap for ListView
    computerBookList = new ArrayList<HashMap<String, String>>();
    new LoadBook().execute();
}

class LoadBook extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Computer.this);
        pDialog.setMessage("Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();

    }

    protected String doInBackground(String... args) {
        List<Book> books=new ArrayList<Book>();

        // Building Parameters

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_books, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("book:", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {


                // books found

                book = json.getJSONArray(TAG_BOOK);

                for (int i = 0; i < book.length(); i++) {
                    JSONObject c = book.getJSONObject(i);

                    // Storing each json item in variable
                    String book_name = c.getString(TAG_BOOK_NAME);
                    String book_price = c.getString(TAG_BOOK_PRICE);
                    String book_id = c.getString(TAG_BOOK_ID);
                    DownloadImage("10.0.2.2/project/images
                     /"+book_id+".png");
                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>(); 

                    // adding each child node to HashMap key => value
                    map.put(TAG_BOOK_NAME, book_name);
                        map.put(TAG_BOOK_PRICE, book_price);
                        // map.put(TAG_AUTHOR_NAME, author_name);

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

                }
                return json.getString(TAG_MESSAGE);
            } else {
                System.out.println("no book found");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        pDialog.dismiss();

        // updating UI from Background Thread
        runOnUiThread(new Runnable() {

            ListView view1 = (ListView) findViewById(R.id.list_view);

            public void run() {

                ImageView iv = (ImageView) findViewById(R.id.list_image);

                    ListAdapter adapter = new SimpleAdapter(Computer.this,
                                computerBookList, R.layout.search_item,
                                new String[] { TAG_BOOK_NAME, TAG_BOOK_PRICE },
                            new int[] { R.id.book_name, R.id.book_price });
                        view1.setAdapter(adapter);


                view1.setAdapter(adapter);

            }
        });

    }

}

private Bitmap DownloadImage(String URL) {
    Bitmap bitmap = null;
    InputStream in = null;
    try {
        in = OpenHttpConnection(URL);
        bitmap = BitmapFactory.decodeStream(in);
        in.close();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    return bitmap;
}

private InputStream OpenHttpConnection(String urlString) throws IOException {
    InputStream in = null;
    int response = -1;

    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();

    if (!(conn instanceof HttpURLConnection))
        throw new IOException("Not an HTTP connection");

    try {
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.connect();
        response = httpConn.getResponseCode();
        if (response == HttpURLConnection.HTTP_OK) {
            in = httpConn.getInputStream();
        }
    } catch (Exception ex) {
        throw new IOException("Error connecting");
    }
    return in;
}

}

3 个答案:

答案 0 :(得分:3)

为了获得更好的模块化体验,首先要定义一个Book类及其属性和方法,例如,这里有一个选项:

public class Book {
    String mName;
    long mPrice;
    Bitmap mPhoto;
}

然后将您的所有图书信息收集到Book列表中(即List<Book>)。 现在是时候为ListView声明自定义适配器了。例如,您可以尝试:

public class CustomAdapter extends ArrayAdapter<Book> {
    public CustomAdapter(Context context, List<Book> books) {
        super(context, 0, books);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        if(row == null) {
            // inflate row layout and assign to 'row'
        }
        final thisBook = getItem(position);
        final ImageView photo = row.findViewById(R.id.photo);
        photo.setImageBitmap(thisBook.mPhoto);

        return row;
    }
}

答案 1 :(得分:1)

使用任何库。

我建议使用picasso

只需从here

下载最新的jar文件

并在适配器的getView()方法中使用此代码

Picasso.with(context)
.load(url)
.placeholder(R.drawable.img_loading)
.error(R.drawable.img_error)
.into(imageView);

答案 2 :(得分:0)

首先将位图(从AsyncTask)存储到Arraylist或任何数据结构。然后,您创建了一个自定义适配器,扩展了"BaseAdapter"类,并将其设置在Listview上,以便您可以在列表中显示这些位图。

可以找到实现自定义适配器here