我想在
ListView
中显示下载的图像。图像是通过函数 DownloadImage
下载的,并且是位图。
如何在
ListView
中显示此内容?
xampp 中 htdocs 文件夹中存储的图像和表格书中带有
book_id
的名称图像是相等的(book_id=100 且名称 image=100.png)。我希望每本书都有自己的图像。
我可以在
ListView
book_name
和 book_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 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;
}
}
首先将位图(来自
AsyncTask
)存储到Arraylist或任何数据结构中。然后,您创建了一个扩展 "BaseAdapter"
类的自定义适配器,并将其设置在您的 Listview
上,以便您可以在列表中显示这些位图。
可以在此处
找到实现自定义适配器