skip to Main Content

From the code below, I am successfully adding data to a list view. I want to add a pagination to the list view. I am getting 5 items in every request and when the user scrolls to bottom, then again, I want to call a web service and get next five items. Also, I want to add a loader to the bottom while getting the data from the server. I tried from code below but failed. How can I achieve this?

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <ListView
                android:id="@+id/listview"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="70dp"
                android:divider="@null" />

        </LinearLayout>

MainActivity.java

public void getTimeLineData(final String token, final String page) {
    timeLineItems = new ArrayList<TimeLineItem>();

    listAdapter = new TimeLineListAdapter(this, timeLineItems);
    listView.setAdapter(listAdapter);


    // These two lines not needed,
    // just to get the look of facebook (changing background color & hiding the icon)
   /* getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
    getActionBar().setIcon(
            new ColorDrawable(getResources().getColor(android.R.color.transparent)));*/

    // We first check for cached request

        String tag_string_req = "req_register";
        // making fresh volley request and getting json
        StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.timeline, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                VolleyLog.d(TAG, "Response: " + response.toString());
                if (response != null) {
                    try {
                        JSONObject jObj = new JSONObject(response);
                        boolean error = jObj.getBoolean("status");
                        String message = jObj.getString("message");
                        if(error){
                            totalPages = jObj.getInt("totalPages");
                            pageCount = jObj.getInt("page");

                            int limit = jObj.getInt("limit");
                            parseJsonFeed(response);
                        }else {
                            Toast.makeText(TimelineActivity.this, message, Toast.LENGTH_SHORT).show();
                        }

                    }catch (Exception e){

                    }

                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting params to register url
                Map<String, String> params = new HashMap<String, String>();
                params.put("my_token", token);
                params.put("page", page);
                params.put("limit", "5");

                return params;
            }
        };

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);

}

private void parseJsonFeed(String response) {
    try {
        JSONObject jsonObj = new JSONObject(response);
        JSONArray feedArray = jsonObj.getJSONArray("data");

        for (int i = 0; i < feedArray.length(); i++) {
            JSONObject feedObj = (JSONObject) feedArray.get(i);

            TimeLineItem item = new TimeLineItem();
            item.setId(feedObj.getInt("id"));
            item.setName(feedObj.getString("name"));
            item.setLname(feedObj.getString("lname"));

            // Image might be null sometimes
            String image = feedObj.isNull("image") ? null : feedObj
                    .getString("image");
            item.setImge(image);
            item.setStatus(feedObj.getString("story_text"));
            item.setProfilePic(feedObj.getString("profile_pic"));
            item.setTimeStamp(feedObj.getString("time_stamp"));
            item.setIsLike(feedObj.getInt("is_like"));
            item.setTotalLikes(feedObj.getString("total_likes"));
            item.setTotalComment(feedObj.getString("total_comments"));

            /*// url might be null sometimes
            String feedUrl = feedObj.isNull("url") ? null : feedObj
                    .getString("url");
            item.setUrl(feedUrl);*/

            timeLineItems.add(item);
        }

        // notify data changes to list adapater
        listAdapter.notifyDataSetChanged();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

//This method will get data from the web api
private void getData() {
    //Adding the method to the queue by calling the method getDataFromServer
    getTimeLineData(token , String.valueOf(requestCount));
    //Incrementing the request counter
    requestCount++;
}

public void timelineScrollItem(){

    listView.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {

        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            if(firstVisibleItem + visibleItemCount == totalItemCount){
                // End has been reached
                getData();
            }
        }
    });

}

2

Answers


  1. replace setOnScrollListener with this

    listView.setOnScrollListener(new OnScrollListener(){
    
       @Override
       public void onScrollStateChanged(AbsListView view, int scrollState) {}
    
       @Override
       public void onScroll(AbsListView view, int firstVisibleItem,
         int visibleItemCount, int totalItemCount) {
    
       int lastInScreen = firstVisibleItem + visibleItemCount;    
       if((lastInScreen == totalItemCount) && !(loadingMore)){     
        getData();
       }
       }
      });
    
    Login or Signup to reply.
  2. You can use this class for

    private class CustomLoadingListItemCreator implements LoadingListItemCreator {
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View view = inflater.inflate(R.layout.custom_loading_list_item, parent, false);
        return new VH(view);
    }
    
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        // Bind custom loading row if needed
      }
    }
    

    You can use this library

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search