简体   繁体   English

如何在Android的Recyclerview中加载更多数据

[英]How to load more data in Recyclerview in android

I am using recyclerview in which I want to fetch more data from server using json. 我正在使用recyclerview,我想在其中使用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 场景是这样的:-第一次点击时,我想在列表中显示5页,而当用户单击第二次点击时显示更多按钮时,则在recyclerview下面显示更多按钮。我该怎么做?

here is my init(): 这是我的init():

    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 > 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);
            }
        }
    });
}

here is my first serevr hit:- 这是我的第一个serevr热门歌曲:-

//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<String, Void, String> {
    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<CDealAppDatastorage>();
                            for (int i = 0; i < 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();

    }
}

here is my second serevr hit 这是我第二次击中

//  sending data and receive reponse on second hit T LOAD MORE DATA  when show more Btn  clicked..............
private class DealNext extends AsyncTask<String, Void, String> {
    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 < 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();


    }
}

here is my adapter class: 这是我的适配器类:

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

public CDealAppListingAdapter(ArrayList<CDealAppDatastorage> 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);
            }
        });

    }

}

} }

Either store two lists in your adapter, the currently displayed list and the full list, or get only the content you need if your API allows it. 在适配器中存储两个列表,即当前显示的列表和完整列表,或者在API允许的情况下仅获取所需的内容。

You can then set your adapter size in getItemCount to be your displayed list size + 1 (for the view more items). 然后,您可以在getItemCount中将适配器大小设置为显示的列表大小+ 1(用于查看更多项目)。 You will need to add a separate view type to return in getItemViewType for your view more cell (the logic to display it would be if the position is currently displayed list size). 您将需要添加一个单独的视图类型以返回getItemViewType以获取更多视图单元格(如果当前位置显示的是列表大小,则显示该逻辑)。 You will also need to add a new view and view holder for the load more cell. 您还需要添加一个新的视图和视图保持器以加载更多单元格。

After you've set up your new view more cell you can simply add a click listener to it, if clicked add 5 items from your full list into your currently displayed list (making sure to start at the currently displayed list - 1 index of the full list, and call notifyDataSetChanged , or notifyItemAdded x 5. 设置新视图更多单元格后,您只需向其添加点击侦听器,如果单击此按钮,则将完整列表中的5项添加到当前显示的列表中(确保从当前显示的列表开始-索引的1个索引)完整列表,然后调用notifyDataSetChangednotifyItemAdded x 5。

I'm sorry I currently don't have time to write an appropriate adapter for you but I hope the above explanation will suffice. 抱歉,我目前没有时间为您编写合适的适配器,但我希望上面的说明就足够了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM