0

First i got data from server and i builded ListView, now i wan't to load more when list view is scrolled to bottom. My async class has name Fetch So i think that i need to call Fetch.execute(); ? Also i need to use all values of Fetch object proprieties that i called first time,

Thanks to all!
My activity code here

public class InboxActivity extends Activity implements View.OnClickListener {


    ......................


    DatePickerDialog.OnDateSetListener d = new DatePickerDialog.OnDateSetListener() {

        ........

        public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {
        ...........     

            this.fetch = new FetchTask();
            this.fetch.Selectedmonth = this.Smonth;
            this.fetch.Selectedyear = this.Syear;
            this.fetch.page = 0;
            this.fetch.sess_id = user_id;
            ListView ll = (ListView)findViewById(R.id.mailList);
            this.fetch.ll = ll;
            this.fetch.execute();
            ll.setOnScrollListener(new OnScrollListener(){


                public void onScrollStateChanged(ListView view, int scrollState)
                {



                }

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




                    if(firstVisibleItem+visibleItemCount==totalItemCount)
                    {

                    HERE I NEED TO LAUNCH FETCH object  

                    }                       

                }



        }
    };






public class FetchTask extends AsyncTask<Void, Void, JSONArray> {

    HERE MY PRORPITIES

        @Override

        protected JSONArray doInBackground(Void... params) {
            try {

                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("my url");

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);


                nameValuePairs.add(new BasicNameValuePair("qw", "er"));
                nameValuePairs.add(new BasicNameValuePair("debug", "1"));
                nameValuePairs.add(new BasicNameValuePair("t", "0"));
                nameValuePairs.add(new BasicNameValuePair("m", Integer.toString(this.Selectedmonth)));
                nameValuePairs.add(new BasicNameValuePair("y", Integer.toString(this.Selectedyear)));
                nameValuePairs.add(new BasicNameValuePair("st", Integer.toString(this.page)));
                nameValuePairs.add(new BasicNameValuePair("sess_id", this.sess_id));


                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));


                HttpResponse response = httpclient.execute(httppost);

                BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "utf-8"), 8);
                StringBuilder sb = new StringBuilder();
                sb.append(reader.readLine());
                String line = "0";
                while ((line = reader.readLine()) != null) 
                {
                    sb.append(line);
                }
                reader.close();
                String result11 = sb.toString();
                System.out.println(result11);
                this.result_str = result11;
                // parsing data
                JSONArray arr = new JSONArray(result11);





                return new JSONArray(result11);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }



          @Override
          protected void onPreExecute() {
              this.pd = new ProgressDialog(InboxActivity.this);
              this.pd.setMessage("loading");
              this.pd.show();         
          } 


        @Override
        protected void onPostExecute(JSONArray result)
        {

            if (result != null) 
            {
                List<String> subjects = new ArrayList<String>();
                List<String> emails = new ArrayList<String>();

                for(int i = 0; i < result.length(); i++)
                {
                    try 
                    {
                        JSONObject json_data = result.getJSONObject(i);
                        emails.add(json_data.getString("mittente"));
                        subjects.add(json_data.getString("oggetto"));
                    } 
                    catch (JSONException e) 
                    {
                        e.printStackTrace();
                    }

                }
                if(this.page == 0)
                {
                    this.adapter = new ArrayAdapter<String>(
                            InboxActivity.this,
                            R.layout.da_item,
                            emails
                        );
                    this.ll.setAdapter(this.adapter);               
                }
                else
                {
                    for(int i = 0; i < result.length(); i++)
                    { 
                        JSONObject json_data;
                        try 
                        {
                            json_data = result.getJSONObject(i);
                            this.adapter.add(json_data.getString("mittente"));  
                        } 
                        catch (JSONException e) 
                        {
                            e.printStackTrace();
                        }

                    }
                }
            } 
            else 
            {
                System.out.println("Messages not found");

            }    
            this.pd.dismiss();
        }
    }   
}
user3323180
  • 43
  • 1
  • 7

2 Answers2

0

Broad overview:

  1. You will need to recreate a new fetch object. You can't re-execute an old AsynTask.

  2. One issue is you don't know how many elements are in your listview, as such the scroll bar will appear as if its reaching the end. Your fetch may come back in time, and you add more elements, and magically there's more to scroll, or it doesn't come back in time, and user reaches the apparent end... If you can determine the total number ahead of time, override the GetCount method.

  3. Deciding when to fetch the next data set. If you override the getView method of your adapter you will be able to get callbacks when the adapter creates a view for each position. As the user scrolls the position will get closer to the end of your array. Set some threshold to begin fetching the next data set.

    class myAdapter extends ArrayAdapter{

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return super.getView(position, convertView, parent);
    
        if(!thresholdReachedBefore && position > threshold){
    
            fetchNextDataSet();
    
        }
    }
    

    }

NameSpace
  • 10,009
  • 3
  • 39
  • 40
  • but i need to recreate new fetch object anytime when i need to load next elements ? – user3323180 Mar 04 '14 at 16:38
  • not only recreate it, but you have to change all the parameters u used to query the first data set, to instead retrieve the second one. Recreating is easy: this.fetch = new FetchTask(); (done!) – NameSpace Mar 04 '14 at 16:42
  • ok, can i get proprieties of my first Fetch object, and than after this.fetch = new FetchTask() pass it like this this.fetch.page = FirstFetchObject.page++; – user3323180 Mar 04 '14 at 16:45
  • that's fine, you just cant' re-execute the async...; obviously u should be setting up your next async to get the data that followed the first query. – NameSpace Mar 04 '14 at 16:48
  • yes, but i can't use my first Fetch object in the onScroll(){} – user3323180 Mar 04 '14 at 16:53
  • don't see why not. Its an internal class referencing a global of the outer class. Try not putting "this." in front of everything, as it returns the "this" for the innermost class. – NameSpace Mar 04 '14 at 17:01
  • the problem is how to pass first fetch object to onScroll method – user3323180 Mar 04 '14 at 17:03
  • you have it as an outterclass global...you don't need to pass it. Unless one of these methods are static? don't see that. – NameSpace Mar 04 '14 at 17:05
  • see referencing the outter class variables [here](http://stackoverflow.com/questions/56974/keyword-for-the-outer-class-from-an-anonymous-inner-class) – NameSpace Mar 04 '14 at 17:11
0

To run your AsyncTask, you will have to call the execute() method of the class extending the AsyncTask. But be careful as each time you do a fetch, you will be fetching a fresh set of original data which might result in duplicates. One way to work around this would be to return only a certain number of elements and keep a count of this. The next time you do a fetch, only fetch the elements from the next index.

ucsunil
  • 7,378
  • 1
  • 27
  • 32