0

It's been a while since I have been using android. can you please tell me how to add OnScrollListener in this code ? Everytime I scroll down I want to fetch 5 more images.

This is the Asyncatask its working correct, but I need fetch 5 image everytime I scroll down(load more).

public class RecyclerOkHttpHandler extends AsyncTask<String, Void, String> {
    private Context mContext;
    private MyInterface mListener;
    public String category;
    public String basestart;
    public String limitend;
    public RecyclerOkHttpHandler(Context context, MyInterface mListener, String categ, String base, String limit){
        mContext = context;
        this.mListener  = mListener;
        category=categ;
        basestart=base;
        limitend=limit;
    }
    public interface MyInterface {
        public void myMethod(ArrayList result);
    }

    private final String Fetch_URL = "http://justedhak.com/old-files/Recyclerview_data.php";
    // ArrayList<Listitem> Listitem;
    ArrayList<CategoryList> Listitem;
    int resulta;

    OkHttpClient httpClient = new OkHttpClient();
    ListView list;
    String myJSON;
    JSONArray peoples = null;
    InputStream inputStream = null;

    @Override
    protected String doInBackground(String... params) {
        Log.d("okhttp Fetch_URL", Fetch_URL);



        RequestBody formBody = new FormEncodingBuilder()
                .add("category", category)
                .add("base", basestart)
                .add("limit", limitend)
                .build();
        Request request = new Request.Builder()
                .url(Fetch_URL)
                .post(formBody)
                .build();


        String result = null;
        try {
            Response response = httpClient.newCall(request).execute();
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            inputStream = response.body().byteStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null)
            {
                sb.append(line + "\n");
            }
            result = sb.toString();
            resulta = 1; //"Success
            //  return response.body().bytes();
        } catch (Exception e) {
            Toast.makeText(mContext, "Connection failed, check your connection",
                    Toast.LENGTH_LONG).show();
            e.printStackTrace();        }
        finally {
            try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
        }
        return result;
    }
    @Override
    protected void onPostExecute(String result){
        if( resulta ==1){
            myJSON=result;
            Log.e("result",result);

            showList();
        }
        else{
            Log.e("d","there is an error on postexecute in okhhttphandler.java");

        }
    }

    protected void showList(){
        try {

            JSONObject jsonObj = new JSONObject(myJSON);
            peoples = jsonObj.getJSONArray("result");
            System.out.println("Length:"+peoples.length());
            int J_length=peoples.length()-1;
            //JSONObject maxj  = peoples.getJSONObject(peoples.length() - 1);
            // max of arrray

            jsonObj= peoples.getJSONObject(J_length);

            String j_id=  jsonObj.getString("id");
            int _id = Integer.parseInt(j_id);
            System.out.println(j_id);

            //max of
            DatabaseHandler db = new DatabaseHandler(mContext);
            String db_id="";
            db_id = db.getmax();
            if (db_id== null)
            {
                db_id="0";
            }
            int d_id = Integer.parseInt(db_id);
            Log.e("db_id", db_id);
            Log.e("j_id",j_id);

            //  if (_id < d_id) {
            System.out.println("Getting json result ");

            Listitem = new ArrayList<CategoryList>();
            for (int i = 0; i < peoples.length(); i++) {
                JSONObject c = peoples.getJSONObject(i);

                String id = c.getString("id");
                String url = c.getString("url");



                Listitem.add(new CategoryList(id, url));
            }

            if (mListener != null)
                mListener.myMethod(Listitem);


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

This is the when I set the adapter

 private String base = "0";
 private String limit = "5";

 final RecyclerOkHttpHandler handler = new RecyclerOkHttpHandler( this, new RecyclerOkHttpHandler.MyInterface() {
            @Override
            public void myMethod(ArrayList result) {
                mAdapter_first = new MyAdapter(result,SearchActivity.this);
                mAdapter_first.notifyDataSetChanged();
                mRecyclerView_first.setAdapter(mAdapter_first);
            }
        },"girls jokes",base,limit);

        try {
             handler.execute().get();

        } catch (Exception e) {
           Log.d("SearchActivity error", "error in mRecyclerView_first");

            e.printStackTrace();
        }
Milad Yarmohammadi
  • 1,253
  • 2
  • 22
  • 37
Moudiz
  • 7,211
  • 22
  • 78
  • 156
  • does your endpoint support pagination? – Blackbelt Sep 04 '16 at 09:33
  • @Blackbelt no it doesnt. just automatic load more – Moudiz Sep 04 '16 at 09:34
  • how do you ask for the next five then ? – Blackbelt Sep 04 '16 at 09:35
  • @Blackbelt its a list view when i scoll down , it will automatic get 5 more images , in `base` and `limit` i specified 5 , in my select statement i added `limist 5` so in android everytime i scoll down i get more images – Moudiz Sep 04 '16 at 09:39
  • In your `AsyncTask`, you load all the data at once? Do you have a limiter in your php file response? – Rachik Abidi Sep 04 '16 at 09:40
  • @RachikAbidi yes i load all data at once with a limit , I have added a limit in my php. I want everytime to load 5 images eveytime i scroll dow – Moudiz Sep 04 '16 at 09:42
  • if you change the limit from 5 to 10, you will always get the old results as well – Blackbelt Sep 04 '16 at 09:42
  • @Blackbelt true , but my problem not in the limit, I want to use `onscrolllistner`. I dont want when the app open to load all the 50 images, i want to load only 5 images, and everytime user scolldown i fetch 5 more did you understand what i want? – Moudiz Sep 04 '16 at 09:45
  • I do. You want pagination. You can find an example [here](https://github.com/bblackbelt/Fyber/blob/master/app/src/main/java/de/fyber/presentation/view/fragments/OfferFragment.java) – Blackbelt Sep 04 '16 at 09:50

1 Answers1

0

For the first load, call your RecyclerOkHttpHandler AsyncTaskto get your first 5 items.

Now, for any further load, all you have to do is to check if the listView is scrolled to its bottom and you can refer to this link Find out if ListView is scrolled to the bottom? to know how to deal with it.

So, each time you detect that the user has scrolled the listview to the bottom, it's time to call the RecyclerOkHttpHandler AsynTask to get the 5 new images.

PS: You need to save the limit you have reached in each load, so that in the next load, you start loading from that limit.

Hope this helps :)

Community
  • 1
  • 1
Rachik Abidi
  • 156
  • 8