android - 如何在 ListView 中显示位图?

标签 android android-listview android-bitmap

我想在 ListView 中显示下载的图像。图像通过函数 DownloadImage 下载,并且是位图。

如何在 ListView 中显示此内容?

存储在xampp中的htdocs文件夹中的图像和表格书中带有book_id的名称图像是相等的(book_id=100和名称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;
}

}

最佳答案

为了体验更好的模块化,首先定义一个 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;
    }
}

关于android - 如何在 ListView 中显示位图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25413227/

相关文章:

android - 47度SwipeListView : Need help to get back the frontview

Android-如何将 android.net.Uri 对象转换为 java.net.URI 对象?

android - 无法在启用混淆器的情况下构建发布版本

android - 如何将 EditText 值传递给 onCreate Android?

java - 在 Android 应用程序中集成 map 时出现错误

具有可变数量的 subview 的android listview行

android - 在 Android 上的 ListView 中突出显示所选项目

android - 如何将位图保存到 Firebase

java - 以编程方式创建图层列表

android - 如果我的应用程序安装在 SD 卡上,私有(private)数据是否也在那里?