How to load more data in Recyclerview in android
<p>I am using recyclerview in which I want to fetch more data from server using json.
scenario is something like that :- On first hit I want to display 5 page in list and a show more button below recyclerview is there when user click show more button on second hit display 5 more pages.how can I do that</p>

<p>here is my init():</p>

<pre><code>    public void init() {
    mProgressBar = (ProgressBar) m_Main.findViewById(R.id.progressBar1);
    mProgressBar.setVisibility(View.GONE);

    m_showMore = (AppCompatButton) m_Main.findViewById(R.id.show_more);
    m_showMore.setBackgroundColor(Color.TRANSPARENT);
    m_showMore.setVisibility(View.GONE);
    // Getting the string array from strings.xml
    m_n_FormImage = new int[]{
            R.drawable.amazon,
            R.drawable.whatsapp,
            R.drawable.zorpia,
            R.drawable.path,
            R.drawable.app_me,
            R.drawable.evernote,
            R.drawable.app_me};

    m_RecyclerView = (RecyclerView) m_Main.findViewById(R.id.my_recycler_view);//finding id of recyclerview
    m_RecyclerView.setItemAnimator(new DefaultItemAnimator());//setting default animation to recyclerview
    m_RecyclerView.setHasFixedSize(true);//fixing size of recyclerview
    mLayoutManager = new LinearLayoutManager(getActivity());
    m_RecyclerView.setLayoutManager(mLayoutManager);//showing odata vertically to user.


    sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// increment of record count
    sz_LastCount = String.valueOf(m_n_DeafalutLastCount);// increment of last count...

    m_Handler = new Handler();
}

public void implementScroll() {// on scroll load more data from server.............
    m_RecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            if (newState == RecyclerView.SCROLL_STATE_IDLE) {

            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if (dy &gt; 0) {

                m_showMore.setVisibility(View.VISIBLE);
                m_showMore.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //change boolean value
                        m_showMore.setVisibility(View.GONE);
                        m_n_DefaultRecordCount = m_n_DefaultRecordCount + 5;// increment of record count by 5 on next load data
                        m_n_DeafalutLastCount = m_n_DeafalutLastCount + 5;// same here.....as above

                        sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// convert int value to string
                        sz_LastCount = String.valueOf(m_n_DeafalutLastCount);// convert int value to string /////
                        new DealNext().execute(m_DealListingURL);// POST DATA TO SERVER TO LOAD MORE DATA......
                    }
                });
            } else {
                m_showMore.setVisibility(View.GONE);
            }
        }
    });
}
</code></pre>

<p>here is my first serevr hit:-</p>

<pre><code>//sending deal data to retreive response from server
public String DealListing(String url, CRegistrationDataStorage login) {
    InputStream inputStream = null;
    m_oJsonsResponse = new CJsonsResponse();
    try {
        // 1. create HttpClient
        HttpClient httpclient = new DefaultHttpClient();
        // 2. make POST request to the given URL
        HttpPost httpPost = new HttpPost(url);
        String json = "";
        // 3. build jsonObject
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("agentCode", m_szMobileNumber);
        jsonObject.put("pin", m_szEncryptedPassword);
        jsonObject.put("recordcount", sz_RecordCount);
        jsonObject.put("lastcountvalue", sz_LastCount);
        //jsonObject.put("emailId", "nirajk1190@gmail.com");
        // 4. convert JSONObject to JSON to String
        json = jsonObject.toString();
        // 5. set json to StringEntity
        StringEntity se = new StringEntity(json);
        // 6. set httpPost Entity
        httpPost.setEntity(se);
        // 7. Set some headers to inform server about the type of the content
        httpPost.setHeader("Content-type", "application/json");
        // 8. Execute POST request to the given URL
        HttpResponse httpResponse = httpclient.execute(httpPost);
        HttpEntity entity = httpResponse.getEntity();
        // 9. receive response as inputStream
        inputStream = entity.getContent();
        System.out.println("InputStream....:" + inputStream.toString());
        System.out.println("Response....:" + httpResponse.toString());

        StatusLine statusLine = httpResponse.getStatusLine();
        System.out.println("statusLine......:" + statusLine.toString());
        ////Log.d("resp_body", resp_body.toString());
        int statusCode = statusLine.getStatusCode();
        // 10. convert inputstream to string
        if (statusCode == 200) {
            // 10. convert inputstream to string
            if (inputStream != null)
                s_szresult = m_oJsonsResponse.convertInputStreamToString(inputStream);
            //String resp_body =
            EntityUtils.toString(httpResponse.getEntity());
        } else
            s_szresult = "Did not work!";
    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }
    System.out.println("resul.....:" + s_szresult);
    // 11. return s_szResult
    return s_szresult;
}

public void getResponse() throws JSONException {// getting response from serevr ..................
    if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Transaction Successful")) {// server based condition

        m_oAdapter = new CDealAppListingAdapter(s_oDataset);// create adapter object and add arraylist to adapter
        m_oAdapter.notifyDataSetChanged();
        m_RecyclerView.setAdapter(m_oAdapter);//adding adapter to recyclerview
    } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {//server based conditions
        CToastMessage.getInstance().showToast(getActivity(), "Connection not avaliable");
    } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Deal List Not Found")) {// serevr based conditions .....
        CToastMessage.getInstance().showToast(getActivity(), "No More Deals Available");
    }
}

//  sending deal data to server and retreive response......
class CDealDataSent extends AsyncTask&lt;String, Void, String&gt; {
    public CRegistrationDataStorage oRegisterStorage;
    public CDealAppDatastorage item;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        CProgressBar.getInstance().showProgressBar(getActivity(), "Please wait while Loading Deals...");
    }

    @Override
    protected String doInBackground(String... urls) {
        return DealListing(urls[0], oRegisterStorage);// sending data to server...

    }

    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(final String result) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                m_Handler.post(new Runnable() {
                    @Override
                    public void run() {
                        CProgressBar.getInstance().hideProgressBar();// hide progress bar after getting response from server.......
                        try {
                            m_oResponseobject = new JSONObject(result);// getting response from server
                            JSONArray posts = m_oResponseobject.optJSONArray("dealList");

                            s_oDataset = new ArrayList&lt;CDealAppDatastorage&gt;();
                            for (int i = 0; i &lt; posts.length(); i++) {
                                JSONObject post = posts.getJSONObject(i);
                                item = new CDealAppDatastorage();
                                item.setM_szHeaderText(post.getString("dealname"));
                                item.setM_szsubHeaderText(post.getString("dealcode"));
                                item.setM_n_Image(m_n_FormImage[i]);
                                s_oDataset.add(item);

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

    }
}
</code></pre>

<p>here is my second serevr hit</p>

<pre><code>//  sending data and receive reponse on second hit T LOAD MORE DATA  when show more Btn  clicked..............
private class DealNext extends AsyncTask&lt;String, Void, String&gt; {
    public CRegistrationDataStorage oRegisterStorage;

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

        mProgressBar.setVisibility(View.VISIBLE);// SHOW PROGRESS BAR
    }

    @Override
    protected String doInBackground(String... urls) {
        //My Background tasks are written here
        synchronized (this) {
            return DealListing(urls[0], oRegisterStorage);// POST DATA TO SERVER
        }
    }

    @Override
    protected void onPostExecute(final String result) {
        super.onPostExecute(result);
        new Thread(new Runnable() {
            @Override
            public void run() {
                m_Handler.post(new Runnable() {
                    @Override
                    public void run() {
                        mProgressBar.setVisibility(View.INVISIBLE);// DISMISS PROGRESS BAR..........
                        try {
                            m_oResponseobject = new JSONObject(result);// getting response from server
                            final JSONArray posts = m_oResponseobject.optJSONArray("dealList");// GETTING DEAL LIST
                            for (int i = 0; i &lt; posts.length(); i++) {
                                JSONObject post = posts.getJSONObject(i);// GETTING DEAL AT POSITION AT I
                                item = new CDealAppDatastorage();// object create of DealAppdatastorage
                                item.setM_szHeaderText(post.getString("dealname"));//getting deal name
                                item.setM_szsubHeaderText(post.getString("dealcode"));// getting deal code
                                item.setM_n_Image(m_n_FormImage[i]);// static image for testing purpose not original....
                                s_oDataset.add(item);// add items to arraylist....
                                m_oAdapter.notifyItemInserted(s_oDataset.size());// notify adapter when deal added to recylerview
                            }
                            getResponse();// getting response from server.....and also here response based logics...


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


    }
}
</code></pre>

<p>here is my adapter class:</p>

<pre><code>public class CDealAppListingAdapter extends RecyclerView.Adapter&lt;RecyclerView.ViewHolder&gt; {
public static CDealAppDatastorage list;
private static ArrayList&lt;CDealAppDatastorage&gt; s_oDataset;
private final int VIEW_TYPE_ITEM = 0;
private final int VIEW_TYPE_LOADING = 1;

public CDealAppListingAdapter(ArrayList&lt;CDealAppDatastorage&gt; mDataList) {
    s_oDataset = mDataList;

}

@Override
public int getItemViewType(int position) {
    return s_oDataset.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    if (i == VIEW_TYPE_ITEM) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.deallisting_card_view, viewGroup, false);
        return new DealAppViewHolder(view);
    } else if (i == VIEW_TYPE_LOADING) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_loading_item, viewGroup, false);
        return new LoadingViewHolder(view);
    }
    return null;

}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    if (holder instanceof DealAppViewHolder) {
        list = s_oDataset.get(position);// receiving item on position on index i
        DealAppViewHolder dealAppViewHolder = (DealAppViewHolder) holder;
        dealAppViewHolder.s_szAppImage.setImageResource(list.getM_n_Image());
        dealAppViewHolder.s_szheadingText.setText(list.getM_szHeaderText());
        dealAppViewHolder.s_szSubHeader.setText(list.getM_szsubHeaderText());
    } else if (holder instanceof LoadingViewHolder) {
        LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
        loadingViewHolder.progressBar.setIndeterminate(true);
    }

}

@Override
public int getItemCount() {
    return (s_oDataset == null ? 0 : s_oDataset.size());//counting size of odata in ArrayList
}

static class LoadingViewHolder extends RecyclerView.ViewHolder {
    public ProgressBar progressBar;

    public LoadingViewHolder(View itemView) {
        super(itemView);
        progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar1);
    }
}

public static class DealAppViewHolder extends RecyclerView.ViewHolder {
    public static ImageView s_szAppImage;
    public static TextView s_szheadingText, s_szSubHeader;
    public static Button s_szGetDealBtn;

    public DealAppViewHolder(View itemLayoutView) {
        super(itemLayoutView);
        s_szheadingText = (TextView) itemLayoutView.findViewById(R.id.headingText);// finding id of headerText...
        s_szSubHeader = (TextView) itemLayoutView.findViewById(R.id.subHeaderText);// finding id of subHeader.....
        s_szAppImage = (ImageView) itemLayoutView.findViewById(R.id.appImage);//finding Id of Imgae in CardView
        s_szGetDealBtn = (Button) itemLayoutView.findViewById(R.id.getDealBtn);// finding id of getdeal Btn

        Random rnd = new Random();//creating object of Random class
        int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));//genrating random color
        s_szGetDealBtn.setBackgroundColor(color);//backgraound color of getDeal Btn
        s_szGetDealBtn.setOnClickListener(new View.OnClickListener() {// onclick getDeal Btn
            @Override
            public void onClick(View v) {//send to deal detail page onclick getDeal Btn
                Intent i = new Intent(v.getContext(), CDealAppListingDetails.class);
                i.putExtra("DealCode", s_oDataset.get(getPosition()).getM_szsubHeaderText());
                i.putExtra("headerText", s_oDataset.get(getPosition()).getM_szHeaderText());
                v.getContext().startActivity(i);
            }
        });

        itemLayoutView.setOnClickListener(new View.OnClickListener() {// onclick cardview
            @Override
            public void onClick(View v) {// onclick cardview send to deal app listing details page .....
                Intent i = new Intent(v.getContext(), CDealAppListingDetails.class);
                i.putExtra("DealCode", list.getM_szsubHeaderText());
                i.putExtra("headerText", list.getM_szHeaderText());
                v.getContext().startActivity(i);
            }
        });

    }

}
</code></pre>

<p>}</p>