【问题标题】:Delete Listview item with Async Class?使用异步类删除 Listview 项目?
【发布时间】:2015-04-19 19:18:54
【问题描述】:

我有我的列表视图,它显示我的本地数据库中的数据库条目。每次单击列表视图项时,我都想删除一行。然后计数器更新并刷新列表。有什么想法吗?

类:

public class ViewAllLocations extends 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);
    locationCount = (TextView) findViewById(R.id.locationCount);

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



  // Get listview
        ListView lo = getListView();
        lo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                new DeleteLocation().execute();
                profileList.remove(position);
            }
        });
    }

    /*****************************************************************
     * 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);
                locationCount.setText(""+profileList.size());

            }
        });

    }

}

【问题讨论】:

  • @AnubianNoob 我无法让它与列表视图匹配?在添加按钮之前,我有一个 onItemClickListener 并运行了异步执行,但我不会收到错误它只是空白并且无法删除任何内容?基于我的代码的任何想法我现在需要用按钮做什么?另外,我不确定如何在刷新列表视图和更新计数器的同时获取选择链接并删除它们?

标签: java android listview android-asynctask


【解决方案1】:

当您成功删除产品后,您还需要从列表中删除该产品。

使用yourList.remove(position) 刷新您的列表。

【讨论】:

  • In,if product if (success == 1) { profileList.remove(position); Toast.makeText(getApplicationContext(), "位置已删除", Toast.LENGTH_SHORT).show();结束(); }
  • @Divya ...它不起作用,无法识别位置...我的列表视图没有真正被引用,而是通过异步类传递...在我的 xml 中它有 id /列表
  • 我重新编辑了这个问题,所以让它变得更容易,基本上我是我列表视图上的一个听众,所以加班我点击它调用我的异步类,并且项目被删除和更新......
  • 查看我的代码,我更改了它...我的列表视图 lo - 我无法为其分配资源 ID/列表?
  • 对不起,不能得到你的确切意图..你为什么要完全使用异步?并从 listview 中删除条目, arraylist.remove(position) 应该可以工作..为了反映更改,您需要使用 notifyDataSetChanged() 方法刷新 listview 的适配器..
猜你喜欢
  • 2014-09-08
  • 2012-06-22
  • 1970-01-01
  • 2019-02-02
  • 1970-01-01
  • 1970-01-01
  • 2016-06-01
  • 1970-01-01
相关资源
最近更新 更多