1

以下代码用于我的 android 应用程序中的一个活动,这仍然是应用程序的概要,因此它不需要太多,但是一旦基本要求到位,我可以进一步进行设计。

这是我的数据库助手类。它进入本地主机,在我的数据库中获取数据,然后将其带回并显示在列表视图中。

  package com.example.parking_guide;

public class DBHelper extends ListActivity {

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

    ArrayList<HashMap<String, String>> productsList;

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

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCTS = "level1";
    private static final String KEY_ROWID = "_id";
    private static final String KEY_VACANT = "vacancy";

    // products JSONArray
    JSONArray table = null;  

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        @SuppressWarnings("unused")
        ListView yourListView = getListView();



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

        // 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> {


        /**
         * 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("level1", json.toString());

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

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

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

                        // Storing each json item in variable
                        String _id = c.getString(KEY_ROWID);
                        String vacant = c.getString(KEY_VACANT);


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


                        // adding each child node to HashMap key => value
                        map.put(KEY_ROWID, _id);
                        map.put(KEY_VACANT, vacant);

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


            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            DBHelper.this, productsList,
                            R.layout.list_item, new String[] { KEY_ROWID,
                                    KEY_VACANT},
                            new int[] { R.id.id, R.id.vac});
                    // updating listview
                    setListAdapter(adapter);
                }
            });

        }

    }
  }'

这段代码可以很好地完成,但我的应用程序稍后会要求它尽可能接近实时服务器,或者至少尝试这样做。所以我需要在几秒钟后(可能少于五秒钟)刷新数据,以保持屏幕上的数据更新。我已经阅读了有关计时器和处理程序的内容,但我无法真正掌握这些概念中的任何一个。任何人都可以帮助我吗?

4

1 回答 1

1

将 ListAdapter 更改为 BaseAdapter;并添加
adapter.notifyDataSetChanged(); 在 ui 上,您可以在 onCreate 中提供注释代码以获得更好的性能

公共类 DBHelper 扩展 ListActivity {

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

ArrayList<HashMap<String, String>> productsList;

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

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "level1";
private static final String KEY_ROWID = "_id";
private static final String KEY_VACANT = "vacancy";

// products JSONArray
JSONArray table = null;  

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    @SuppressWarnings("unused")
    ListView yourListView = getListView();



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

BaseAdapter adapter = new SimpleAdapter(
                    DBHelper.this, productsList,
                    R.layout.list_item, new String[] { KEY_ROWID,
                            KEY_VACANT},
                    new int[] { R.id.id, R.id.vac});
             updating listview
            setListAdapter(adapter);

    // 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> {


    /**
     * 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("level1", json.toString());

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

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

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

                    // Storing each json item in variable
                    String _id = c.getString(KEY_ROWID);
                    String vacant = c.getString(KEY_VACANT);


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


                    // adding each child node to HashMap key => value
                    map.put(KEY_ROWID, _id);
                    map.put(KEY_VACANT, vacant);

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


        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
             adapter.notifyDataSetChanged();
            }
        });

    }

}

}'

于 2012-10-08T04:33:30.307 回答