Search code examples
androidandroid-listviewandroid-bitmap

How to display bitmaps in listview?


I want to show downloaded images in a ListView. Images are downloaded with a function DownloadImage and are bitmaps.

How do I show this in a ListView?

Images stored in folder htdocs in xampp and name images with book_id in a table book are equal(book_id=100 and name image=100.png).I want each book to have its own image.

I can show in the ListView book_name and book_price. The problem is with the image book.

class:

    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;
}

}

Solution

  • For better modularity, first of all define a Book class with its properties and methods:

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

    Then collect all of your books information into a list of Book(i.e List<Book>). Now it's time to define a custom adapter for the ListView. For example:

    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 the row layout and assign it to 'row'.
            }
            final thisBook = getItem(position);
            final ImageView photo = row.findViewById(R.id.photo);
            photo.setImageBitmap(thisBook.mPhoto);
    
            return row;
        }
    }