使用id / list在Textview中显示Listview计数?

时间:2015-04-19 16:15:09

标签: java android listview android-listview count

我正在从localhost服务器的listview中加载我的数据。我想在textview(locationCount)中显示计数。有任何想法吗?

我的listview有id / list,它是为加载产品的异步类引用的。因此,如果您将其视为普通列表视图或稍有不同,我会感到有点困惑?

我的数据库中有20个条目显示,因此计数应为20,但是当我删除条目时,计数应为19,如果我添加,则为21。请解释一下?

类别: 公共类ViewAllLocations扩展了ListActivity {

String id;

// Progress Dialog
private ProgressDialog pDialog;

// JSON parser class
JSONParser jsonParser = new JSONParser();

ArrayList<HashMap<String, String>> profileList;

// url to get all products list
private static String url_all_profile = "http://MYIP:8888/android_connect/get_all_location.php";
// url to delete product
private static final String url_delete_profile = "http://MYIP:8888/android_connect/delete_location.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_LOCATION = "Location";
private static final String TAG_ID = "id";
private static final String TAG_LATITUDE = "latitude";
private static final String TAG_LONGITUDE = "longitude";


// products JSONArray
JSONArray userprofile = null;

TextView locationCount;
int count = 0;
Button deleteLocation;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_all_locations);
    // Hashmap for ListView
    profileList = new ArrayList<HashMap<String, String>>();

    deleteLocation = (Button) findViewById(R.id.deleteLocation);

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

    deleteLocation.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new DeleteLocation().execute();
        }
    });
    // Get listview
    ListView lo = getListView();
    getListAdapter().getCount();
    locationCount.setText(getListAdapter().getCount());



}




/*****************************************************************
 * Background Async Task to Delete Product
 * */
class DeleteLocation extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(ViewAllLocations.this);
        pDialog.setMessage("Deleting Location...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    /**
     * Deleting product
     * */
    protected String doInBackground(String... args) {

        // Check for success tag
        int success;
        try {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("id", id));

            // getting product details by making HTTP request
            JSONObject json = jsonParser.makeHttpRequest(
                    url_delete_profile, "POST", params);

            // check your log for json response
            Log.d("Delete Product", json.toString());

            // json success tag
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                // product successfully deleted
                // notify previous activity by sending code 100
               // Intent i = getIntent();
                // send result code 100 to notify about product deletion
                //setResult(100, i);
                Toast.makeText(getApplicationContext(), "Location Deleted",
                        Toast.LENGTH_SHORT).show();
                finish();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once product deleted
        pDialog.dismiss();

    }

}

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

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(ViewAllLocations.this);
        pDialog.setMessage("Loading Locations. 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 = jsonParser.makeHttpRequest(url_all_profile, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("All Profiles: ", json.toString());

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

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

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

                    // Storing each json item in variable
                    String id = c.getString(TAG_ID);
                    String latitude = c.getString(TAG_LATITUDE);
                    String longitude = c.getString(TAG_LONGITUDE);


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

                    // adding each child node to HashMap key => value
                    map.put(TAG_ID, id);
                    map.put(TAG_LATITUDE, latitude);
                    map.put(TAG_LONGITUDE, longitude);


                    // adding HashList to ArrayList
                    profileList.add(map);
                }
            } else {
                // no products found
                // Launch Add New product Activity
                Intent i = new Intent(getApplicationContext(),
                        UserLocation.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(
                        ViewAllLocations.this, profileList,
                        R.layout.locationitem, new String[] { TAG_ID,
                        TAG_LATITUDE, TAG_LONGITUDE},
                        new int[] { R.id.id, R.id.latitude, R.id.longitude});
                // updating listview
                setListAdapter(adapter);
            }
        });

    }

}

记录:&#34;它获取配置文件,然后当它到达最终结束时崩溃&#34;

04-19 19:09:48.665  26876-27452/com.example.ankhit.saveme D/All Profiles:﹕ {"success":1,"Location":[{"id":"26","longitude":"-0.5509257","latitude":"51.4276462"},{"id":"27","longitude":"-0.5509387","latitude":"51.4277023"},{"id":"28","longitude":"-0.5509387","latitude":"51.4277023"},{"id":"29","longitude":"-0.550991","latitude":"51.4275759"}]}
04-19 19:09:48.675  26876-26876/com.example.ankhit.saveme D/AndroidRuntime﹕ Shutting down VM
04-19 19:09:48.675  26876-26876/com.example.ankhit.saveme W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x42008ac8)
04-19 19:09:48.675  26876-26876/com.example.ankhit.saveme E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.NullPointerException
            at com.example.ankhit.saveme.ViewAllLocations$LoadAllLocation$1.run(ViewAllLocations.java:260)
            at android.app.Activity.runOnUiThread(Activity.java:4843)
            at com.example.ankhit.saveme.ViewAllLocations$LoadAllLocation.onPostExecute(ViewAllLocations.java:246)
            at com.example.ankhit.saveme.ViewAllLocations$LoadAllLocation.onPostExecute(ViewAllLocations.java:165)
            at android.os.AsyncTask.finish(AsyncTask.java:631)
            at android.os.AsyncTask.access$600(AsyncTask.java:177)
            at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:176)
            at android.app.ActivityThread.main(ActivityThread.java:5299)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
            at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:0)

覆盖适配器中的get count()方法或在此处发布,我会给你一些代码。

无论何时添加或删除项目,都要调用adapter.get count()。