user2573690
user2573690

Reputation: 5983

How to clear data in ListView? AsyncTask

I have the following AsyncTask in a Fragment and would like to clear the listview and repopulate it when a button is clicked. Here is what I have tried:

The button click:

btnRefresh.setOnClickListener(new View.OnClickListener() {
    @Override
public void onClick(View view) {
    lv.setAdapter(null);
        new LoadAllProducts().execute();
}
});

And here is my AsyncTask:

class LoadAllProducts extends AsyncTask<String, String, String> {

    //ListView lv = (ListView) rootView.findViewById(R.id.list);
    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        lv.setAdapter(null);
        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Loading your trips. 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_trips, "GET", params);

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

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

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

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

                    // Storing each json item in variable
                    String tripid = c.getString(TAG_TRIPID);
                    String tripname = c.getString(TAG_TRIPNAME);
                    String userId = c.getString("uid");

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

                    if (userId.equals(db.getUserDetails().get("uid"))) {
                        // adding each child node to HashMap key => value
                        map.put(TAG_TRIPID, tripid);
                        map.put(TAG_TRIPNAME, tripname);

                        // adding HashList to ArrayList
                        tripList.add(map);
                    } //else {
                        //map.put(TAG_TRIPID, "");
                        //map.put(TAG_TRIPNAME, "You have no tracked trips.");

                        //tripList.add(map);
                    //}
                }
            } else {
                // no products found
                // Launch Add New product Activity
                Intent i = new Intent(getActivity(),
                        NewTrip_Activity.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
        ((Activity) getActivity()).runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */


                ListAdapter adapter = new SimpleAdapter(
                        getActivity(), tripList,
                        R.layout.list_item, new String[] { TAG_TRIPID,
                                TAG_TRIPNAME, "TEST"},
                        new int[] { R.id.pid, R.id.name, R.id.mileage });
                // updating listview
                ((ListView) lv.findViewById(R.id.list)).setAdapter(adapter);
            }
        });
     }
 }

Problem is that clicking the button clears the listview but then adds twice the items back. So what was already in the listview plus the same items again. If you click the button again, it adds the items a third time!

I know I must be missing something but all I find online is using a ArrayAdapter rather than ListAdapter. Thanks for any help solving this!

Upvotes: 1

Views: 6056

Answers (6)

Piyush
Piyush

Reputation: 18933

After your AsyncTask is executed you can clear your arraylist

tripList.clear();
adapter.notifyDataSetChanged();

or you can set adapter null also

lv.setAdapter(null);
adapter.notifyDataSetChanged();

Upvotes: 1

John
John

Reputation: 8946

You have to referesh the Listview after setting null in adapter

btnRefresh.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View view) {
    lv.setAdapter(null);
    adapter.notifyDataSetChanged();
    new LoadAllProducts().execute();
 }
});

Upvotes: 0

Jerry Wattre
Jerry Wattre

Reputation: 204

do adpater.clear(); and tripList.clear();

Upvotes: 1

Prachi
Prachi

Reputation: 2559

You have to declare adapter globally and used its instance to clear data and then fill it again

Upvotes: 0

Nambi
Nambi

Reputation: 12042

You need to Clear the tripList.clear() your tripList(arraylist) before add the map to them tripList.add(map) otherwise it will add to the existing old value

Upvotes: 2

keshav
keshav

Reputation: 3255

Make adapter global

 ListAdapter adapter ;

And change onClick to this

public void onClick(View view) {
              new LoadAllProducts().execute();
              adapter.notifyDataSetChanged();
}

Also you need to check tripList that its not appending the list before adding items make it clear.

Upvotes: 2

Related Questions