如何在android中的listview中放置2个字符串和从数据库中获取的图像

时间:2013-07-03 19:05:39

标签: android json url listview imageview

我有一个数据库,其中存储2个文本字符串和图像的URL。我的问题是如何从该URL下载图像并将其与2个字符串放入listview项目。我的代码获取字符串并从链接下载图像,但图像不会显示在列表视图中。

public class NotificariActivity extends ListActivity {

// Progress Dialog
private ProgressDialog pDialog;

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

ArrayList<HashMap<String, Object>> productsList;

// url to get all products list
private static String url_not = "http://gtc.flavdesign.com/get_notificari.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "notificari";
private static final String TAG_PID = "id";
private static final String TAG_TEXT = "text";
private static final String TAG_DATE = "data";
private static final String TAG_LINK = "link";

// products JSONArray
JSONArray products = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.all_oferte);

    // Hashmap for ListView
    productsList = new ArrayList<HashMap<String, Object>>();

    // Loading products in Background Thread
    new LoadAllProducts().execute();

}

/**
 * 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(NotificariActivity.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_not, "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 text = c.getString(TAG_TEXT);
                    String date = c.getString(TAG_DATE);
                    String link = c.getString(TAG_LINK);

                    // creating new HashMap
                    HashMap<String, Object> map = new HashMap<String, Object>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_PID, id);
                    map.put(TAG_TEXT, text);
                    map.put(TAG_DATE, date);

                    Bitmap bitmap;
                    try
                    {
                    URL url = new URL(link);
                    HttpGet httpRequest = null;
                    httpRequest = new HttpGet(url.toURI());
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
                    HttpEntity entity = response.getEntity();
                    BufferedHttpEntity b_entity = new BufferedHttpEntity(entity);
                    InputStream input = b_entity.getContent();
                    bitmap = BitmapFactory.decodeStream(input); 
                    }
                    catch(Exception e)
                    {
                        bitmap=Bitmap.createBitmap(null);
                    }

                    map.put("IMAGE",bitmap);


                    // adding HashList to ArrayList
                    productsList.add(map);
                }
            }
        } 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();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        NotificariActivity.this, productsList,
                        R.layout.list_oferte, new String[] { TAG_PID,
                                TAG_TEXT, TAG_DATE, "IMAGE"},
                        new int[] { R.id.pid, R.id.text, R.id.date, R.id.imageView1});

                // updating listview
                setListAdapter(adapter);
            }
        });

    }

}
}

List Item的我的XML文件如下所示:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >

<!-- Product id (pid) - will be HIDDEN - used to pass to other activity -->

<!-- Name Label -->

     <TextView
         android:id="@+id/pid"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:textColor="#FFFFFF"
         android:visibility="gone" />

     <TextView
         android:id="@+id/text"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:paddingLeft="6dip"
         android:paddingTop="6dip"
         android:textSize="17dip"
         android:textColor="#FFFFFF"
         android:textStyle="bold" />

     <TextView
         android:id="@+id/date"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:paddingLeft="6dip"
         android:paddingTop="6dip"
         android:textSize="17dip"
         android:textColor="#FFFFFF"
         android:textStyle="bold" />

     <ImageView
         android:id="@+id/imageView1"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:src="@android:drawable/gallery_thumb" />

</LinearLayout>

1 个答案:

答案 0 :(得分:0)

我无法使用SimpleAdapter。文档说

  

ImageView的。预期的绑定值是资源ID或字符串,并调用setViewImage(ImageView,int)或setViewImage(ImageView,String)。

但是在构造函数的文档中:

  

应在“from”参数中显示列的视图。这些都应该是TextViews。

但是,通过扩展BaseAdapter来实现它并不困难,它为您提供了一些灵活性:

我将此添加到NotificariActivity类:

public class ProductAdapter extends BaseAdapter {
    // Hashmap for ListView
    ArrayList<HashMap<String, Object>> productsList = new ArrayList<HashMap<String, Object>>();

    @Override public int getCount() { return productsList.size(); }

    @Override public Object getItem(int position) { return position; }

    @Override public long getItemId(int position) { return (Long) productsList.get(position).get(TAG_PID); }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.list_oferte, null);
            holder = new ViewHolder();
            holder.pid = (TextView)convertView.findViewById(R.id.pid);
            holder.text = (TextView)convertView.findViewById(R.id.text);
            holder.date = (TextView)convertView.findViewById(R.id.date);
            holder.img = (ImageView)convertView.findViewById(R.id.imageView1);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder)convertView.getTag();
        }
        holder.pid.setText((String)productsList.get(position).get(TAG_PID));
        holder.text.setText((String)productsList.get(position).get(TAG_TEXT));
        holder.date.setText((String)productsList.get(position).get(TAG_DATE));
        holder.img.setImageBitmap((Bitmap)productsList.get(position).get("IMAGE"));
        return convertView;
    }

    private class ViewHolder {
        public TextView pid, text, date;
        public ImageView img;
    }
}
private LayoutInflater mInflater;
ProductAdapter pa = new ProductAdapter();

这是在超级调用之后的onCreate方法中:

mInflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

然后productsList.add(map);变为pa.productsList.add(map);。在那之后,我能够看到一张笑脸和“测试sa moara familia mea。”