我创建了一个listview来从PHP服务器加载图像和文本。我编写的代码运行良好,没有错误,但我的listview是空白的,不显示任何图像或文本。
LazyAdapter.java
package mygp.gptrade.imageListAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import mygp.gptrade.AllProductActivity;
import mygp.gptrade.R;
import mygp.gptrade.image.ImageLoader;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.list_item, null);
TextView pid = (TextView)vi.findViewById(R.id.pid);
TextView itemname = (TextView)vi.findViewById(R.id.name);
TextView price = (TextView)vi.findViewById(R.id.price);
ImageView thumb_image = (ImageView)vi.findViewById(R.id.imageView1); //
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(position);
pid.setText(song.get(AllProductActivity.TAG_PID));
itemname.setText(song.get(AllProductActivity.TAG_NAME));
price.setText(song.get(AllProductActivity.TAG_PRICE));
imageLoader.DisplayImage(song.get(AllProductActivity.TAG_PATH), thumb_image); //
return vi;
}
}
AllProductActivity.java
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 mygp.gptrade.imageListAdapter.LazyAdapter;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class AllProductActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser2 jParser = new JSONParser2();
ArrayList<HashMap<String, String>> productsList;
ListView list;
LazyAdapter adapter;
// url to get all products list
private static String url_all_products = "http://gemini888.tk/test4/android_connect/get_all_products.php";
// JSON Node names
public static final String TAG_SUCCESS = "success";
public static final String TAG_PRODUCTS = "products";
public static final String TAG_PID = "uid";
public static final String TAG_NAME = "itemname";
public static final String TAG_PRICE = "price";
public static final String TAG_PATH = "path";
// products JSONArray
JSONArray products = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
list = (ListView)findViewById(android.R.id.list);
//testing
if (android.os.Build.VERSION.SDK_INT > 9)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// on seleting single product
// launching Edit Product Screen
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllProductActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String iname = c.getString(TAG_NAME);
String price = c.getString(TAG_PRICE);
String path = c.getString(TAG_PATH);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, iname);
map.put(TAG_PRICE, price);
map.put(TAG_PATH, path);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
adapter=new LazyAdapter(AllProductActivity.this, productsList);
list.setAdapter(adapter);
}
});
}
}
}
ImageLoader.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import mygp.gptrade.R;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
public class ImageLoader {
MemoryCache memoryCache=new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
public ImageLoader(Context context){
fileCache=new FileCache(context);
executorService=Executors.newFixedThreadPool(5);
}
final int stub_id=R.drawable.ic_launcher;
public void DisplayImage(String url, ImageView imageView)
{
imageViews.put(imageView, url);
Bitmap bitmap=memoryCache.get(url);
if(bitmap!=null)
imageView.setImageBitmap(bitmap);
else
{
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, ImageView imageView)
{
PhotoToLoad p=new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}
private Bitmap getBitmap(String url)
{
File f=fileCache.getFile(url);
//from SD cache
Bitmap b = decodeFile(f);
if(b!=null)
return b;
//from web
try {
Bitmap bitmap=null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is=conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Throwable ex){
ex.printStackTrace();
if(ex instanceof OutOfMemoryError)
memoryCache.clear();
return null;
}
}
//decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f){
try {
//decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE=210;
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
//decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}
//Task for the queue
private class PhotoToLoad
{
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i){
url=u;
imageView=i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad){
this.photoToLoad=photoToLoad;
}
@Override
public void run() {
if(imageViewReused(photoToLoad))
return;
Bitmap bmp=getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if(imageViewReused(photoToLoad))
return;
BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
Activity a=(Activity)photoToLoad.imageView.getContext();
a.runOnUiThread(bd);
}
}
boolean imageViewReused(PhotoToLoad photoToLoad){
String tag=imageViews.get(photoToLoad.imageView);
if(tag==null || !tag.equals(photoToLoad.url))
return true;
return false;
}
//Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable
{
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
public void run()
{
if(imageViewReused(photoToLoad))
return;
if(bitmap!=null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
}
AllProduct.php
<?php
/*
* Following code will list all the products
*/
// array for JSON response
$response = array();
// include db connect class
require_once 'include/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all products from products table
$result = mysql_query("SELECT *FROM image_detail") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["products"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["uid"] = $row["uid"];
$product["itemname"] = $row["itemname"];
$product["price"] = $row["price"];
$product["description"] = $row["description"];
// push single product into final response array
array_push($response["products"], $product);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";
// echo no users JSON
echo json_encode($response);
}
?>
LOG
05-15 03:44:07.809: D/All Products:(1248): {"success":1,"products": [{"uid":"1","itemname":"Sdsda","description":"Dsadasdasd","price":"0.00"},{"uid":"2","itemname":"Gagagaga","description":"Gagagaga","price":"0.00"},{"uid":"3","itemname":"Gtr 35","description":"Rm30","price":"0.00"},{"uid":"4","itemname":"Lycan Hypersport","description":"Rm 40","price":"0.00"},{"uid":"5","itemname":"laptop asus","description":"so cheap","price":"20.00"},{"uid":"6","itemname":"xiaomi3","description":"condition 9\/10","price":"50.00"},{"uid":"7","itemname":"acer laptop","description":"freeeeee wajajaja","price":"10.00"},{"uid":"8","itemname":"dell laptop","description":"for sell","price":"60000.00"},{"uid":"9","itemname":"abyss kang","description":"grab it fast","price":"3000000.00"},{"uid":"10","itemname":"botol","description":"cheap je mari la","price":"1.00"},{"uid":"11","itemname":"diao nsksjs","description":"sghsjsjs","price":"444.00"},{"uid":"12","itemname":"cook","description":"cook","price":"20.00"},{"uid":"13","itemname":"cookw","description":"cookw","price":"20.00"},{"uid":"14","itemname":"hahahhaha","description":"hahahhahaa","price":"20.00"},{"uid":"15","itemname":"bola","description":"football yes la","price":"10.00"},{"uid":"16","itemname":"try","description":"try","price":"20.00"},{"uid":"17","itemname":"try2","description":"try2","price":"25.00"},{"uid":"18","itemname":"try3","description":"try3","price":"555.00"},{"uid":"19","itemname":"try4","description":"try4","price":"0.00"},{"uid":"20","itemname":"try5","description":"try5","price":"5.00"},{"uid":"21","itemname":"try6","description":"try6","price":"555.00"},{"uid":"22","itemname":"try7","description":"try7","price":"0.00"},{"uid":"23","itemname":"try8","description":"try8","price":"25.00"},{"uid":"24","itemname":"try9","description":"try9","price":"0.00"},{"uid":"25","itemname":"trt10","description":"trt10","price":"25.00"},{"uid":"26","itemname":"tryee","description":"rrrf","price":"0.00"},{"uid":"27","itemname":"trydd","description":"fff","price":"0.00"},{"uid":"28","itemname":"sr-","description":"dftycfyyhhhy","price":"0.00"},{"uid":"29","itemname":"display flow","description":"display flow","price":"20.00"},{"uid":"30","itemname":"yamcha","description":"yamcha","price":"0.00"},{"uid":"31","itemname":"louis","description":"louis","price":"0.00"}]}
05-15 03:44:07.809: W/System.err(1248): org.json.JSONException: No value for path
05-15 03:44:07.819: W/System.err(1248): at org.json.JSONObject.get(JSONObject.java:355)
05-15 03:44:07.819: W/System.err(1248): at org.json.JSONObject.getString(JSONObject.java:515)
05-15 03:44:07.819: W/System.err(1248): at mygp.gptrade.AllProductActivity$LoadAllProducts.doInBackground(AllProductActivity.java:166)
05-15 03:44:07.909: I/Choreographer(1248): Skipped 99 frames! The application may be doing too much work on its main thread.
05-15 03:44:07.999: I/Choreographer(1248): Skipped 47 frames! The application may be doing too much work on its main thread.
05-15 03:44:08.089: W/System.err(1248): at mygp.gptrade.AllProductActivity$LoadAllProducts.doInBackground(AllProductActivity.java:1)
05-15 03:44:08.179: I/Choreographer(1248): Skipped 47 frames! The application may be doing too much work on its main thread.
05-15 03:44:08.449: I/Choreographer(1248): Skipped 37 frames! The application may be doing too much work on its main thread.
05-15 03:44:08.529: W/System.err(1248): at android.os.AsyncTask$2.call(AsyncTask.java:288)
05-15 03:44:08.529: W/System.err(1248): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
05-15 03:44:08.579: I/Choreographer(1248): Skipped 59 frames! The application may be doing too much work on its main thread.
05-15 03:44:08.649: I/Choreographer(1248): Skipped 32 frames! The application may be doing too much work on its main thread.
05-15 03:44:08.729: I/Choreographer(1248): Skipped 30 frames! The application may be doing too much work on its main thread.
05-15 03:44:08.789: I/Choreographer(1248): Skipped 32 frames! The application may be doing too much work on its main thread.
05-15 03:44:08.879: I/Choreographer(1248): Skipped 34 frames! The application may be doing too much work on its main thread.
05-15 03:44:08.939: I/Choreographer(1248): Skipped 31 frames! The application may be doing too much work on its main thread.
05-15 03:44:09.039: I/Choreographer(1248): Skipped 31 frames! The application may be doing too much work on its main thread.
05-15 03:44:09.299: I/Choreographer(1248): Skipped 44 frames! The application may be doing too much work on its main thread.
05-15 03:44:09.379: W/System.err(1248): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
05-15 03:44:09.379: W/System.err(1248): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
05-15 03:44:09.429: I/Choreographer(1248): Skipped 61 frames! The application may be doing too much work on its main thread.
05-15 03:44:09.499: I/Choreographer(1248): Skipped 42 frames! The application may be doing too much work on its main thread.
05-15 03:44:09.599: I/Choreographer(1248): Skipped 43 frames! The application may be doing too much work on its main thread.
05-15 03:44:09.859: I/Choreographer(1248): Skipped 38 frames! The application may be doing too much work on its main thread.
05-15 03:44:10.049: I/Choreographer(1248): Skipped 42 frames! The application may be doing too much work on its main thread.
05-15 03:44:10.069: W/System.err(1248): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
05-15 03:44:10.069: W/System.err(1248): at java.lang.Thread.run(Thread.java:841)
05-15 03:44:10.109: I/Choreographer(1248): Skipped 36 frames! The application may be doing too much work on its main thread.
05-15 03:44:10.319: I/MemoryCache(1248): MemoryCache will use up to 12.0MB
05-15 03:44:10.359: I/Choreographer(1248): Skipped 162 frames! The application may be doing too much work on its main thread.
答案 0 :(得分:0)
添加此
$product["path"] = $row["path"];
内
while ($row = mysql_fetch_array($result)) {
希望这能解决你的问题。