尝试填充listview但模拟器中没有显示任何内容

时间:2015-02-27 04:19:53

标签: android listview android-listview

我正在尝试填充listview,但模拟器中没有显示任何错误。

这是我的MainActivity

public class MainActivity 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/callarocket/get_all.php";

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

        // products JSONArray
        JSONArray products = null;

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

            // 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 AdapterView.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(MainActivity.this);
                pDialog.setMessage("Loading requests. 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 Requests: ", 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);

                            // 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);

                            // 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();
                // updating UI from Background Thread
                runOnUiThread(new Runnable() {
                    public void run() {
                        /**
                         * Updating parsed JSON data into ListView
                         * */
                        ListAdapter adapter = new SimpleAdapter(
                                MainActivity.this, productsList,
                                R.layout.single_list, new String[] { TAG_PID,
                                TAG_NAME},
                                new int[] { R.id.jid, R.id.name });
                        // updating listview
                        setListAdapter(adapter);
                    }
                });

            }

        }
}

这是我的ListView

<?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">
    <!-- Main ListView
         Always give id value as list(@android:id/list)
    -->
    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

这是我的single_list.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/jid"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:visibility="gone" />

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

</LinearLayout>

这是logcat

02-27 04:09:28.998    2954-2974/com.example.user.rocket W/System.err﹕ org.json.JSONException: No value for products
02-27 04:09:28.998    2954-2974/com.example.user.rocket W/System.err﹕ at org.json.JSONObject.get(JSONObject.java:389)
02-27 04:09:28.998    2954-2974/com.example.user.rocket W/System.err﹕ at org.json.JSONObject.getJSONArray(JSONObject.java:584)
02-27 04:09:28.998    2954-2974/com.example.user.rocket W/System.err﹕ at com.example.user.rocket.MainActivity$LoadAllProducts.doInBackground(MainActivity.java:143)
02-27 04:09:28.998    2954-2974/com.example.user.rocket W/System.err﹕ at com.example.user.rocket.MainActivity$LoadAllProducts.doInBackground(MainActivity.java:109)
02-27 04:09:28.998    2954-2974/com.example.user.rocket W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:288)
02-27 04:09:28.998    2954-2974/com.example.user.rocket W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:237)
02-27 04:09:28.998    2954-2974/com.example.user.rocket W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
02-27 04:09:28.998    2954-2974/com.example.user.rocket W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
02-27 04:09:28.998    2954-2974/com.example.user.rocket W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
02-27 04:09:28.999    2954-2974/com.example.user.rocket W/System.err﹕ at java.lang.Thread.run(Thread.java:818)

我正在尝试使用JSONParser从MySQL数据库填充listview。该应用程序能够运行,但模拟器中没有显示任何数据。我试过谷歌搜索这个错误org.json.JSONException: No value for products,但我找不到任何可以解决这个问题的解决方案。

0 个答案:

没有答案