Android 带有 MySQL 数据库的惰性列表加载器

Android Lazy List Loader with MySQL database

我只是 Android 编程的新手。我在论文中使用 Fedor 的 LazyList。我一直在尝试配置他的代码,但我没有得到任何运气。我想做的是从 mysql 检索数据并将其放入文本视图中。但是,我只为所有文本视图获取相同的最后数据,我不确定为什么第三个是空的。

我的LogCat显示我正在从数据库中获取所有数据,所以问题一定是代码结构。

代码:

Lazy_ListItem.java

public class Lazy_ListItem extends Activity {

    ListView list;
    Lazy_Adapter adapter;

    // Progress Dialog
    private ProgressDialog pDialog;

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

    ArrayList<HashMap<String, String>> productsList;

    // url to get all products list
    // private static String url_all_products =
    // "http://10.0.2.2/android_connect/get_all_products.php";
    private static String url_all_products = "http://10.0.2.2/restosnapp/get_all_products.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_DRINKS = "drinks";
    private static final String TAG_RID = "rid";
    private static final String TAG_DRK_ID = "drk_id";
    private static final String TAG_DRK_NAME = "drk_name";
    private static final String TAG_DRK_DESC = "drk_desc";
    private static final String TAG_DRK_PRICE = "drk_price";
    private static final String TAG_DRK_AVAIL = "drk_avail";
    private static final String TAG_DRK_IMAGE = "drk_image";

    // products JSONArray
    JSONArray drinks = null;

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

        list = (ListView) findViewById(R.id.list);
        adapter = new Lazy_Adapter(this, mStrings);
        list.setAdapter(adapter);

        // Button b = (Button) findViewById(R.id.button1);
        // b.setOnClickListener(listener);

    }

    @Override
    public void onDestroy() {
        list.setAdapter(null);
        super.onDestroy();
    }

    /*public OnClickListener listener = new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            adapter.imageLoader.clearCache();
            adapter.notifyDataSetChanged();
        }
    };*/

    private String[] mStrings = {
            "http://webitprojects.com/restaurant/images/drinks/drk_coffee.jpg",
            "http://webitprojects.com/restaurant/images/drinks/drk_calamansijuice.jpg",
            "http://webitprojects.com/restaurant/images/drinks/drk_blackgulaman.jpg",
            "http://webitprojects.com/restaurant/images/drinks/drk_avocadoshake.jpg",
            "http://webitprojects.com/restaurant/images/drinks/drk_durianshake.jpg" };
}

Lazy_Adapter.java

public class Lazy_Adapter extends BaseAdapter {

    TextView tvMenuName, tvMenuDesc, tvMenuPrice;
    String drk_name, drk_desc, drk_price, drk_avail;
    int length;

    // Progress Dialog
    private ProgressDialog pDialog;

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

    ArrayList<HashMap<String, String>> productsList;

    // url to get all products list
    // private static String url_all_products =
    // "http://10.0.2.2/android_connect/get_all_products.php";
    private static String url_all_products = "http://10.0.2.2/restosnapp/get_all_products.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_DRINKS = "drinks";
    private static final String TAG_RID = "rid";
    private static final String TAG_DRK_ID = "drk_id";
    private static final String TAG_DRK_NAME = "drk_name";
    private static final String TAG_DRK_DESC = "drk_desc";
    private static final String TAG_DRK_PRICE = "drk_price";
    private static final String TAG_DRK_AVAIL = "drk_avail";
    private static final String TAG_DRK_IMAGE = "drk_image";

    // products JSONArray
    JSONArray drinks = null;

    private Activity activity;
    private String[] data;
    private static LayoutInflater inflater = null;
    public Lazy_ImageLoader imageLoader;

    public Lazy_Adapter(Activity a, String[] d) {
        activity = a;
        data = d;
        inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        imageLoader = new Lazy_ImageLoader(activity.getApplicationContext());

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

    public int getCount() {
        return data.length;
    }

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

    public long getItemId(int position) {
        return position;
    }

    // ///

    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
    class LoadAllProducts extends AsyncTask<String, String, String> {

        /**
         * 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 response
            Log.d("All Drinks: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    drinks = json.getJSONArray(TAG_DRINKS);

                    // looping through All Products
                    for (int i = 0; i < drinks.length(); i++) {
                        JSONObject c = drinks.getJSONObject(i);
                        length = drinks.length();
                        // Storing each json item in variable
                        String rid = c.getString(TAG_RID);
                        String drk_id = c.getString(TAG_DRK_ID);
                        drk_name = c.getString(TAG_DRK_NAME);
                        drk_desc = c.getString(TAG_DRK_DESC);
                        drk_price = c.getString(TAG_DRK_PRICE);
                        drk_avail = c.getString(TAG_DRK_AVAIL);

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

                        // adding each child node to HashMap key => value
                        // map.put(TAG_RID, rid);
                        // map.put(TAG_DRK_ID, drk_id);
                        // map.put(TAG_DRK_NAME, drk_name);
                        // map.put(TAG_DRK_DESC, drk_desc);
                        // map.put(TAG_DRK_PRICE, drk_price);
                        // adding HashList to ArrayList
                        // productsList.add(map);
                    }
                    }
            }catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }}

    }

    public View getView(int position, View convertView, ViewGroup parent) {
        View vi = convertView;
        if (convertView == null)
            vi = inflater.inflate(R.layout.item, null);

        // text.setText("Drinks " + position);
        //TextView tvMenuName = (TextView) vi.findViewById(R.id.tvMenuName);

        ImageView image = (ImageView) vi.findViewById(R.id.image);
        imageLoader.DisplayImage(data[position], image);
        TextView tvMenuName = (TextView) vi.findViewById(R.id.tvMenuName);
        tvMenuName.setText(drk_name);
        TextView tvMenuDesc = (TextView) vi.findViewById(R.id.tvMenuDesc);
        tvMenuDesc.setText(drk_desc);
        TextView tvMenuPrice = (TextView) vi.findViewById(R.id.tvMenuPrice);
        tvMenuPrice.setText("P" + drk_price);
        TextView tvMenuAvail = (TextView) vi.findViewById(R.id.tvMenuAvail);
        tvMenuAvail.setText(drk_avail);

        return vi;
    }
}

希望你能帮助我。谢谢。

更新:将代码更改为此并且有效!

/**
 * Background Async Task to Load all product by making HTTP Request
 * */
class LoadAllProducts extends AsyncTask<String, String, String> {

    /**
     * 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 response
        Log.d("All Drinks: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // products found
                // Getting Array of Products
                drinks = json.getJSONArray(TAG_DRINKS);

                // looping through All Products
                for (int i = 0; i < drinks.length(); i++) {
                    JSONObject c = drinks.getJSONObject(i);

                    // Storing each json item in variable
                    drk_name = c.getString(TAG_DRK_NAME);
                    drk_desc = c.getString(TAG_DRK_DESC);
                    drk_price = c.getString(TAG_DRK_PRICE);
                    drk_avail = c.getString(TAG_DRK_AVAIL);

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

                    // adding each child node to HashMap key => value

                    map.put(TAG_DRK_NAME, drk_name);
                    map.put(TAG_DRK_DESC, drk_desc);
                    map.put(TAG_DRK_PRICE, drk_price);
                    map.put(TAG_DRK_AVAIL, drk_avail);

                    // adding HashList to ArrayList
                    productsList.add(map);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

}

public View getView(int position, View convertView, ViewGroup parent) {
    View vi = convertView;
    if (convertView == null)
        vi = inflater.inflate(R.layout.item, null);

    for (Map<String, String> menuItem : productsList) {
        ImageView image = (ImageView) vi.findViewById(R.id.image);
        imageLoader.DisplayImage(data[position], image);
        TextView tvMenuName = (TextView) vi.findViewById(R.id.tvMenuName);
        tvMenuName.setText(productsList.get(position).get(TAG_DRK_NAME));
        TextView tvMenuDesc = (TextView) vi.findViewById(R.id.tvMenuDesc);
        tvMenuDesc.setText(productsList.get(position).get(TAG_DRK_DESC));
        TextView tvMenuPrice = (TextView) vi.findViewById(R.id.tvMenuPrice);
        tvMenuPrice.setText(productsList.get(position).get(TAG_DRK_PRICE));
        TextView tvMenuAvail = (TextView) vi.findViewById(R.id.tvMenuAvail);
        tvMenuAvail.setText(productsList.get(position).get(TAG_DRK_AVAIL));

    }

    return vi;
}

看起来在 getView() 方法中,当您需要从 productsList 中提取数据时,您正在从已设置为 class 字段的变量中提取数据相反。

尝试更换 tvMenuName.setText(drk_name);tvMenuName.setText(productsList.get(position).get(TAG_DRK_NAME));

以此类推...

您看到的是所有 TextViews 中数据的最后一部分,因为在 AsyncTask 中的循环中,您每次都设置相同的变量,如下所示。您需要在循环的每次迭代中清酒这些。例如,您可以在 List 中使用 HashMap。在 getView 方法中执行类似 productsList.get(position).get(TAG_DRK_NAME) 等的操作。您实际上已将其中大部分注释掉。

drk_name = c.getString(TAG_DRK_NAME);
drk_desc = c.getString(TAG_DRK_DESC);
drk_price = c.getString(TAG_DRK_PRICE);
drk_avail = c.getString(TAG_DRK_AVAIL);