Search code examples
javaandroidgithub-api

How get all results from github search api?


I need to get all results with github search api with pagination using. Now I use request: https://api.github.com/search/repositories?q=lib&page=1&per_page=20 I read that the responses also includes the Link header which contains a ready-made URL to the next page. In response I have link https://api.github.com/search/repositories?q=lib&page=2&per_page=20> and link to the last page: https://api.github.com/search/repositories?q=java&page=50&per_page=20 But I don't understand how can I to implement transition to the next page using these links.


Solution

  • You can create a variable to keep track of your current page. & increment it on the success each time until your list size becomes equal to total_count.

    on RecyclerView end reached method can be called again.

    I have tried to demonstrate the example as following please use the actual calls & stuff that you're using. just understand the pattern.

    public class MainActivity extends AppCompatActivity {
    
        private int page = 1;
    
        private ArrayList<Object> items = new ArrayList<>();
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            call();
        }
        
        //dummy call
        private void call(){
            String url = "https://api.github.com/search/repositories?q=lib&page=" + page + "&per_page=20";
            //pass the new url with page to call or just params as per your need
            new ResponseListener(url){
                @Override
                public void onSuccess(ArrayList<Object> list,Integer totalCount) {
                    //parse & add items
                    items.addAll(list);
                    //check if you have items same as total count.
                    // If true then it means you've reached the end
                    if (items.size() < totalCount){
                        //increase the page number for next call
                        page++;
                    }
                }
    
                @Override
                public void onError(Exception e) {
                    e.printStackTrace();
                }
            };
        }
    
    
    }