ListView没有显示任何内容

时间:2014-02-26 14:15:05

标签: android listview

我试图从mysql数据库中显示项目的列表视图。我得到了正确的JSON响应,但我的listview没有显示任何内容。有什么问题?

这是要显示的内容的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 -->
<TextView
    android:id="@+id/pid"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:visibility="gone" />

<!-- Name Label -->
<TextView
    android:id="@+id/name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingTop="6dip"
    android:paddingLeft="6dip"
    android:textSize="17sp"
    android:textStyle="bold" />

<TextView 
    android:id="@+id/budget"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
</LinearLayout>

列表活动的布局:

<?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="fill_parent"
android:orientation="vertical">

<ListView
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>

</LinearLayout>

这是它的代码:

public class DisplayReqItem extends ListActivity {

// 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:8000/project/display_req.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "product";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_BUDGET = "price";

// products JSONArray
JSONArray products = null;

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

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

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

    // Get listview
    ListView lv = getListView();

    // on seleting single product
    // launching Edit Product Screen
    lv.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(),
                    MainMenu.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(DisplayReqItem.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 name = c.getString(TAG_NAME);
                    String budget = c.getString(TAG_BUDGET);

                    // 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, name);
                    map.put(TAG_BUDGET, budget);

                    // adding HashList to ArrayList
                    productsList.add(map);
                }
            } else {
                // no products found
                // Launch Add New product Activity
                Intent i = new Intent(getApplicationContext(),
                        MainMenu.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();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        DisplayReqItem.this, productsList,
                        R.layout.activity_display_requested, new String[] { TAG_PID,
                                TAG_NAME, TAG_BUDGET},
                        new int[] { R.id.pid, R.id.name, R.id.price });
                // updating listview
                setListAdapter(adapter);
            }
        });

    }
}}`

2 个答案:

答案 0 :(得分:0)

方法onPostExecute()用于更新UI,因此无需运行后台线程来执行此操作。

更新 - 为您创建了一个自定义适配器,因此请尝试按如下所示更改onPostExecute()并将此类ProductsAdapter添加到您的项目中

更新2 - &gt;&gt;我的所有Code to Now都使用了Product Class而不是HashMap,我不认为你需要在这里使用HashMap所以试试这段代码吧。希望这就是你现在所需要的一切

如果所有Else失败,处理任何事情的最佳方法是构建自定义

onPostExecute()方法:

/**
 * After completing background task Dismiss the progress dialog
 * **/
protected void onPostExecute(String file_url) {
    // dismiss the dialog after getting all products
    pDialog.dismiss();

     if(productsList.size() > 0){
            /**
             * Updating parsed JSON data into ListView
             * */

           // Added a Custom Adapter instead of SimpleAdapter
            ProductsAdapter adapter = new ProductsAdapter(getBaseContext(), productsList);

            if(getListView() != null){

               // updating listview
              setListAdapter(adapter);
           }else{
               Log.d("ListView-Reference", "ListView is null");
           }
      }else{
                Log.d("Product List", "Products list is empty");
          }
   }

自定义适配器类

public class ProductsAdapter extends BaseAdapter {


private Arraylist<Product> m_productsList = null;
private LayoutInflater mInflater = null;

private class Row{

    TextView mTextViewPID;
    TextView mTextViewName;
    TextView mTextViewPrice;


}


public ProductsAdapter(Context context, Arraylist<Product> productsList){
    this.mInflater = LayoutInflater.from(context);
    this.m_productsList = productsList;

}


// --------------------------------------------------
// BaseAdapter Overrides
// --------------------------------------------------

@Override
public int getCount() {
    int count = 0;

    if((m_productsList !=null) && (m_productsList.size() >= 1)){

        count = m_productsList.size();

    }

    return count;
}

@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return m_productsList.get(position);
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    Row theRow;

    // If ConvertVIew is null
    if(convertView == null){

        theRow = new Row();

        convertView = mInflater.inflate(R.layout.activity_display_requested, null);

        theRow.mTextViewPID         = (TextView) convertView.findViewById(R.id.pid);
        theRow.mTextViewName        = (TextView) convertView.findViewById(R.id.name);
        theRow.mTextViewPrice       = (TextView) convertView.findViewById(R.id.budget);


        convertView.setTag(theRow);

    }else{

        theRow = (Row) convertView.getTag();
    }


    theRow.mTextViewPID.setText(m_productsList.get(position).pid);
    theRow.mTextViewName.setText(m_productsList.get(position).name);
    theRow.mTextViewPrice.setText(m_productsList.get(position).budget);



    return convertView;
}

添加产品类

public class Product{

 // Simple Variables for this Item
 public int pid = -1;
 public String name = null;
 public String budget = null;

} 

我不确定为什么要为这些值而不是对象使用HashMap但这就是我要做的事情

然后使用ArrayList而不是使用HashMap,如下所示:

使用产品对象的ArrayList而不是Hashmap

ArrayList<Product> productsList = new ArrayList<Product>();

新的doInBackground()方法

  /**
 * 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 name = c.getString(TAG_NAME);
                String budget = c.getString(TAG_BUDGET);

                // Create a new Product Obect, set its Values
                Product mProduct = new Product();
                mProduct.pid = id;
                mProduct.name = name;
                mProduct.budget = budget;

                // adding Product to ArrayList
                productsList.add(mProduct);
            }
        } else {
            // no products found
            // Launch Add New product Activity
            Intent i = new Intent(getApplicationContext(),
                    MainMenu.class);
            // Closing all previous activities
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(i);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return null;
}

答案 1 :(得分:0)

在自定义适配器类“SimpleAdapter”中,您必须覆盖方法getCount()

此方法返回要创建的列表视图行数,这是 productsList

的大小

所以请在productsList.size()方法中返回getCount()

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