1

I have a ArrayAdapter that gathers information from an AsyncTask. The AsyncTask is triggered by an on scroll listener. When the user scrolls to the bottom of the content the AsyncTask is triggered and loads more content. The problem is I have implemented a reset button. What this does is clears the ArrayAdapter and resets the tokens that are sent through JSON to a php script that gathers the information. The reset button doesn't work at all. When I call clear() it sometimes clears the list and then adds new data but then the onScrollListener doesn't work or it doesn't clear the list and just adds new data to the top of the list. Here is my code, all of this code is in the same activity.

GLOBAL CLASS FOR TOKENS SENT TO PHP SCRIPT

class CommentInfo {

                  public CommentInfo() {}
                  private String commentID;
                  private int gatheredComments;
                  private int totalComments;

                  public String getCommentID(){
                    return commentID;
                  }
                  public void setCommentID(String c){
                    commentID = c;
                  }

                  public int getGatheredComments(){
                        return gatheredComments;
                      }
                      public void setGatheredComments(int forNumber){
                        gatheredComments = forNumber;
                      }


                }//end commentInfor class
            final CommentInfo info = new CommentInfo();
            info.setCommentID("0");

This class contains Global Variables. CommentID is set to 0. This is sent to a php script via Json. After it gathers a group of comments it resets the CommentID to the ID of the last comment gathered. When the Reset button is clicked it resets the CommentID to 0, as if the Activity has just began.

ASYNCTASK THAT GATHERS COMMENTS AND USES GLOBAL VARIABLES

class loadComments extends AsyncTask<JSONObject, String, JSONObject> {



                @Override
                protected void onPreExecute() {
                    super.onPreExecute();

                    progDailog.getWindow().setGravity(Gravity.BOTTOM);
                    progDailog.setIndeterminate(false);
                    progDailog.setCancelable(false);
                    progDailog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                    progDailog.show();
                    progDailog.setContentView(R.layout.progress_circle);





                } 

                @Override
                protected void onProgressUpdate(String... values) {
                    super.onProgressUpdate(values);

                } 

                protected JSONObject doInBackground(JSONObject... params) {


                    JSONObject json2 = CollectComments.collectComments(usernameforcomments, info.getCommentID());


                        return json2;



                }

                @Override
                protected void onPostExecute(JSONObject json2) {

                    progDailog.dismiss();

                    try {  
                        if (json2.getString(KEY_SUCCESS) != null) { 
                            registerErrorMsg.setText("");
                            String res2 = json2.getString(KEY_SUCCESS);
                            if(Integer.parseInt(res2) == 1){ 



                                JSONArray commentArray = json2.getJSONArray(KEY_COMMENT);
                                String comments[] = new String[commentArray.length()];
                                for ( int i=0; i<commentArray.length(); i++ ) {
                                    comments[i] = commentArray.getString(i);
                                }
                                JSONArray contentsArray = json2.getJSONArray(KEY_CONTENT);
                                String contents[] = new String[contentArray.length()];
                                for ( int i=0; i<contentArray.length(); i++ ) {
                                    contents[i] = contentArray.getString(i); 
                                }
                                JSONArray usernameArray = json2.getJSONArray(KEY_USERNAME);
                                String usernames[] = new String[usernameArray.length()];
                                for ( int i=0; i<usernameArray.length(); i++ ) {
                                    usernames[i] = usernameArray.getString(i);
                                }


                             final List <Item> tempList2 = new ArrayList <Item>();

                            String tempForNumber = json2.getString(KEY_COMMENTS_GATHERED);
                             int forNumber = Integer.parseInt(tempForNumber);

                                for (int x = 0; x < forNumber;x++){
                                    tempList2.add (new Item (usernames [x], contents[x], comments[x]));
                                  }




                                customAdapter.addAll(tempList2);

                                String commentID = json2.getString(KEY_COMMENT_ID);

                                info.setCommentID(commentID);
                                info.setGatheredComments(forNumber);

                                if (info.getTotalComments() >= Integer.parseInt(json2.getString(KEY_NUMBER_OF_COMMENTS))){     

                                    int tempNum = Integer.parseInt(json2.getString(KEY_NUMBER_OF_COMMENTS));
                                    info.setTotalComments(tempNum);

                                }


                                  try
                                  {

                                              Thread.sleep(1000);
                                  }
                                                      catch(Exception e) 
                                                      {
                                                          e.printStackTrace();
                                                      } 

                                }//end if key is == 1
                            else{
                                // Error in registration
                                registerErrorMsg.setText(json2.getString(KEY_ERROR_MSG));
                            }//end else
                        }//end if
                    } //end try

                    catch (JSONException e) { 
                        e.printStackTrace();
                    }//end catch


                }


            }

The Asynctask gathers multiple items and places them into an ArrayAdapter. This ArrayAdapter is what I try and clear but it never works out right.

THIS IS THE ON SCROLL LISTENER THAT ACTIVATES THE ASYNCTASK

class EndlessScrollListener implements OnScrollListener {
                private int visibleThreshold = 5;
                private boolean loading = true;

                public EndlessScrollListener() {
                }
                public EndlessScrollListener(int visibleThreshold) {
                    this.visibleThreshold = visibleThreshold;
                }

                @Override
                public void onScroll(AbsListView view, int firstVisibleItem,
                        int visibleItemCount, int totalItemCount) {


                   if (loading) {
                        if (totalItemCount > previousTotal) {
                           loading = false;
                            previousTotal = totalItemCount;
                        }
                }
                    if (!loading && (firstVisibleItem + visibleItemCount) == totalItemCount) {

                        new loadComments().execute();
                        loading = true;
                    }




                }

                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {
                } 
            }

I believe the problem is occurring because of something in this class. I am not sure what I believe its in there. Maybe because the variables below aren't resetting or something.

int firstVisibleItem,int visibleItemCount, int totalItemCount

THIS IS HOW I RESET THE ARRAYADAPTER

refresh = (ImageView) findViewById(R.id.refresh);

            refresh.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if(customAdapter!= null)
                    {
                        customAdapter.clear();
                        info.setCommentID("0");
                        info.setGatheredComments(0);
                        yourListView.smoothScrollToPosition(0);
                        new loadComments().execute();

                    }

                }
            });

custom Adapter is the name of my adapter and youListView is the name of my ListView. Please someone help to explain why the adapter doesn't clear and if it does the OnScrollListener ceases to work.

Rumit Patel
  • 8,830
  • 18
  • 51
  • 70

5 Answers5

5

After calling Adapter.clear() you need to call Adapter.notifyDataSetChanged()

Basically whenever the data backing the adapter changes, you need to call Adapter.notifyDataSetChanged() to reflect the changes on the ListView.

Varun
  • 33,833
  • 4
  • 49
  • 42
  • 1
    I have done this and it makes sure the listView is cleared but, the onscrollListener wont work. –  Aug 30 '13 at 00:56
  • 1
    Well. if your list is empty then there nothing to scroll. Isn't that obvious. – Varun Aug 30 '13 at 01:02
  • 1
    Actually I placed the code `new loadComments().execute();` is called once I hit reset so it adds new data to the listView. It adds the same data as if the activity was just started but the onScrollListener doesn't work. It acts as if the contents of the ArrayAdapter still exists. –  Aug 30 '13 at 01:05
  • what exactly do you mean when you say that "onScrollListener doesn't work". What do you expect it to do>? – Varun Aug 30 '13 at 01:42
  • Its suppose to call the AsyncTask when it reaches the bottom of the ListView. It calculates how many Items are in the listView and then can detect when the last View is showing. It then calls the AsyncTask. The problem is it doesn't know I cleared the list and counts the other Views as part of the total amount of Views so it doesn't detect that I am at the bottom of the listView –  Aug 30 '13 at 05:16
  • well i guess that should be posted as another question if your scroll listener is getting removed or something. – Varun Aug 30 '13 at 23:56
1

If you do any filter before, you need to call Adapter.getFilter().filter(""); before call Adapter.notifyDataSetChanged();

Nam Nguyen
  • 71
  • 1
  • 8
0

Just came across a similar problem. It seems re-instantiating and re-attaching the Scroll Listener after the List.clear() and after the ListAdapter.notifyDataSetChanged(); solves the problem.

Perhaps the Listener is junked after List.clear()?

MisterJimson
  • 480
  • 4
  • 5
0

Sometimes that does not work. You can also remove all items from the view. And then repopulate.

    final int adapterCount = adapter.getCount();

    for (int i = 0; i < adapterCount; i++) {
        View item = adapter.getView(i, null, null);
        myLayout.removeView(item);
    }
Coen Damen
  • 2,009
  • 5
  • 29
  • 51
0

Try to remove the listview´s OnScrollListener when you call the asynctask and set it back when the asynctask finishes its job.

Michel Fortes
  • 819
  • 8
  • 12