Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

endless scroll list view in android

I want to create Endless scroll view , list view data coming from server. i am created but when add new data then list view visible item started from start. And when add more than 70 rows then application crashed and error say array index out of bound. I am new in android i am not able to use git hub library.

Please any one help me provide a simple example of endless list view or tutorial to use git hub library.

there my asyn class code

 private class AlertSearchAsync extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {
          String response = "";
          for (String url : urls) {
            DefaultHttpClient client = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            try {
              HttpResponse execute = client.execute(httpGet);
              InputStream content = execute.getEntity().getContent();

              BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
              String s = "";
              while ((s = buffer.readLine()) != null) {
                response += s;
              }

            } catch (Exception e) {
              e.printStackTrace();
            }
          }
          return response;
        }

        @Override
        protected void onPostExecute(String result) {
            //pd.dismiss();
            if(result.trim().contains("Result not found !"))
            {
                Toast.makeText(getApplicationContext(), result.trim(), Toast.LENGTH_LONG).show();
                return;

            }
            else
            {

                mylist = new ArrayList<String>();

                 doc = XMLfunctions.XMLfromString(result);

                // Toast.makeText(getApplicationContext(), ""+line, Toast.LENGTH_LONG).show();

                 NodeList nodes = doc.getElementsByTagName("JOB");

                    for (int i = 0; i < nodes.getLength(); i++) {
                        Element e = (Element) nodes.item(i);
                        pass_value.add(XMLfunctions.getValue(e, "id"));

                        if (!("null").equals(XMLfunctions.getValue(e, "location"))) {
                            mylist.add(XMLfunctions.getValue(e, "location"));
                            city_name.add(XMLfunctions.getValue(e, "location"));


                        } else {
                            mylist.add(" ");
                        }
                        if (!("null").equals(XMLfunctions.getValue(e, "title"))) {
                            mylist.add(XMLfunctions.getValue(e, "title"));
                            business_name.add(XMLfunctions.getValue(e, "title"));



                        } else {
                            mylist.add(" ");
                        }
                        if (!("null").equals(XMLfunctions.getValue(e, "state"))) {
                            mylist.add(XMLfunctions.getValue(e, "state"));
                            state_name.add(XMLfunctions.getValue(e, "state"));



                        } else {
                            mylist.add(" ");
                        }

                        if (!("null").equals(XMLfunctions.getValue(e, "company"))) {
                            mylist.add(XMLfunctions.getValue(e, "company"));
                            company_name.add(XMLfunctions.getValue(e, "company"));


                        } else {
                            mylist.add(" ");
                        }


                         if (!("null").equals(XMLfunctions.getValue(e, "url"))) {
                                mylist.add(XMLfunctions.getValue(e, "url"));
                                url_list.add(XMLfunctions.getValue(e, "url"));


                            } else {
                                mylist.add(" ");
                            }
                         if (!("null").equals(XMLfunctions.getValue(e, "description"))) {
                                mylist.add(XMLfunctions.getValue(e, "description"));
                                desc_list.add(XMLfunctions.getValue(e, "description"));


                            } else {
                                mylist.add(" ");
                            }

                    }

                    String[] company = new String[company_name.size()];
                    company = company_name.toArray(company);

                    String[] position = new String[business_name.size()];
                    position = business_name.toArray(position);
                    String[] state = new String[state_name.size()];
                    state = state_name.toArray(state);
                    String[] city = new String[city_name.size()];
                    city = city_name.toArray(city);

                    String[] url_str = new String[url_list.size()];
                    url_str = url_list.toArray(url_str);

                   String[] desc_str1 = new String[desc_list.size()];
                    desc_str1 = desc_list.toArray(desc_str1);
                   // datadap.setNotifyOnChange(false); // Prevents 'clear()' from clearing/resetting the listview
                    datadap.clear();
                    datadap= new Data(contect,company,position,city,state,pass_value,desc_str1);
                   // listView.setStackFromBottom(true);

                   // datadap.notifyDataSetChanged();
                    listView.setAdapter(datadap);


            /*  str_loc=str_locAlert;
                str_desc=str_descAlert;
                Toast.makeText(getApplicationContext(), "alert Class"+str_desc+str_loc, Toast.LENGTH_LONG).show();
                Intent i= new Intent(Main_listview.this,Main_listview.class);
                i.putExtra("line", result);
                i.putExtra("limit", limit);
                i.putExtra("Alert", true);
                i.putExtra("str_Descrption",str_desc);
                i.putExtra("str_location", str_loc);
                startActivity(i);     */
            }

        }

        @Override
        protected  void onPreExecute()
        {
            //pd = ProgressDialog.show(Main_listview.this, "","Please wait...");

        }
      }

and i am load more data like this

listView.setOnScrollListener(new EndlessScrollListener() {
                @Override
                public void onLoadMore(int page, int totalItemsCount) {
                        // Triggered only when new data needs to be appended to the list
                        // Add whatever code is needed to append new items to your AdapterView
                    limit=limit+10;
                    // TODO Auto-generated method stub



                    AlertSearchAsync task1=new AlertSearchAsync();
                    String url="http://www.jobdiagnosis.com/fjobsrchservise.php?keyword="+
                            str_descAlert+
                            "&location="+str_locAlert+
                            "&start="+limit;
                    url=url.replace(" ", "%20");
                    //Toast.makeText(getApplicationContext(),"Limit"+limit, Toast.LENGTH_LONG).show();
                    task1.execute(url);
                    Log.d("URL ", url);
                }
                });

there my endlessscrollistner class

public abstract class EndlessScrollListener implements OnScrollListener {
// The minimum amount of items to have below your current scroll position
// before loading more.
private int visibleThreshold = 5;
// The current offset index of data you have loaded
private int currentPage = 0;
// The total number of items in the dataset after the last load
private int previousTotalItemCount = 0;
// True if we are still waiting for the last set of data to load.
private boolean loading = true;
// Sets the starting page index
private int startingPageIndex = 0;

public EndlessScrollListener() {
}

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

public EndlessScrollListener(int visibleThreshold, int startPage) {
    this.visibleThreshold = visibleThreshold;
    this.startingPageIndex = startPage;
    this.currentPage = startPage;
}

// This happens many times a second during a scroll, so be wary of the code you place here.
// We are given a few useful parameters to help us work out if we need to load some more data,
// but first we check if we are waiting for the previous load to finish.
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
    // If the total item count is zero and the previous isn't, assume the
    // list is invalidated and should be reset back to initial state
    // If there are no items in the list, assume that initial items are loading
    if (!loading && (totalItemCount < previousTotalItemCount)) {
        this.currentPage = this.startingPageIndex;
        this.previousTotalItemCount = totalItemCount;
        if (totalItemCount == 0) { this.loading = true; } 
    }

    // If it’s still loading, we check to see if the dataset count has
    // changed, if so we conclude it has finished loading and update the current page
    // number and total item count.
    if (loading) {
        if (totalItemCount > previousTotalItemCount) {
            loading = false;
            previousTotalItemCount = totalItemCount;
            currentPage++;
        }
    }

    // If it isn’t currently loading, we check to see if we have breached
    // the visibleThreshold and need to reload more data.
    // If we do need to reload some more data, we execute onLoadMore to fetch the data.
    if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
        onLoadMore(currentPage + 1, totalItemCount);
        loading = true;
    }
}

// Defines the process for actually loading more data based on page
public abstract void onLoadMore(int page, int totalItemsCount);

@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
    // Don't take any action on changed
}

}

I am relay sorry about my bad English

Please help me how we can create endless scroll list view

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think I might implement this the way that @commonsware does in this example: https://github.com/commonsguy/cwac-endless

Basically you create a ListView and attach an Adapter that automatically handles the endless scrolling and loading of Views.

See the class file here: https://github.com/commonsguy/cwac-endless/blob/master/src/com/commonsware/cwac/endless/EndlessAdapter.java


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...