Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

recyclerView.setOnScrollChangeListener not working

this is my fragment code. i m usimg this code for endless recycler view which is get the data from server when scroll the recycler view item. but the code is not working. in this code recyclerView.setOnScrollChangeListener() not working it shows error view cannot be applied to android.content .context. how to use the setOnScrollChangeListener in fragment to load the data from server when scroll the list.

    public class Fragment1 extends Fragment implements 
    RecyclerView.OnScrollChangeListener{
    //Creating a List of superheroes
     private List<SuperHero> listSuperHeroes;

     //Creating Views
     private RecyclerView recyclerView;
     private RecyclerView.LayoutManager layoutManager;
     private RecyclerView.Adapter adapter;
     public ProgressBar progressBar;

     //Volley Request Queue
      private RequestQueue requestQueue;

       //The request counter to send ?page=1, ?page=2  requests
       private int requestCount = 1;

       public Fragment1() {}

       @Override
        public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        }

      @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup 
        container, Bundle savedInstanceState) {
         // Inflate the layout for this fragment
         View view= inflater.inflate(R.layout.activity_main, container, 
       false);
       //Initializing Views
       recyclerView.setLayoutManager(layoutManager);

    //Initializing our superheroes list
    listSuperHeroes = new ArrayList<>();
    requestQueue = Volley.newRequestQueue(getContext());

    //Calling method to get data to fetch data
    getData();

    //Adding an scroll change listener to recyclerview
    recyclerView.setOnScrollChangeListener(getActivity());

    //initializing our adapter
    adapter = new CardAdapter(listSuperHeroes, getActivity());

    //Adding adapter to recyclerview
    recyclerView.setAdapter(adapter);
 progressBar = (ProgressBar) view.findViewById(R.id.progressBar1);
    return view;
}

//Request to get json from server we are passing an integer here
//This integer will used to specify the page number for the request ?page = requestcount
//This method would return a JsonArrayRequest that will be added to the request queue
private JsonArrayRequest getDataFromServer(int requestCount) {
    //Initializing ProgressBar


    //Displaying Progressbar
   // progressBar.setVisibility(View.VISIBLE);
    //setProgressBarIndeterminateVisibility(true);

    //JsonArrayRequest of volley
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL + String.valueOf(requestCount),
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    //Calling method parseData to parse the json response

                    Log.e("response",response.toString());
                    parseData(response);
                    //Hiding the progressbar
                    progressBar.setVisibility(View.GONE);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    progressBar.setVisibility(View.GONE);
                    //If an error occurs that means end of the list has reached
                    Toast.makeText(getActivity(), "No More Items Available", Toast.LENGTH_SHORT).show();
                }
            });

    //Returning the request
    return jsonArrayRequest;
}

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

//This method will parse json data
private void parseData(JSONArray array) {
    for (int i = 0; i < array.length(); i++) {
        //Creating the superhero object
        //int a= array.length();
        //String s=String.valueOf(a);
        //Log.e("array",s);
        SuperHero superHero = new SuperHero();
        JSONObject json = null;
        try {
            //Getting json
            json = array.getJSONObject(i);

            //Adding data to the superhero object
            superHero.setImageUrl(json.getString(Config.TAG_IMAGE_URL));
            //superHero.setName(json.getString(Config.TAG_NAME));
            //superHero.setPublisher(json.getString(Config.TAG_PUBLISHER));
            superHero.setMglId(json.getString(Config.TAG_MGLID));
            superHero.setAgeHeight(json.getString(Config.TAG_AGEHEIGHT));
            superHero.setCommunity(json.getString(Config.TAG_COMMUNITY));
            superHero.setOccupation(json.getString(Config.TAG_OCCUPATION));
            superHero.setIncome(json.getString(Config.TAG_INCOME));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //Adding the superhero object to the list
        listSuperHeroes.add(superHero);
    }

    //Notifying the adapter that data has been added or changed
    adapter.notifyDataSetChanged();
}

//This method would check that the recyclerview scroll has reached the bottom or not
private boolean isLastItemDisplaying(RecyclerView recyclerView) {
    if (recyclerView.getAdapter().getItemCount() != 0) {
        int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
        if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
            return true;
    }
    return false;
}

//Overriden method to detect scrolling
@Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
    //Ifscrolled at last then
    if (isLastItemDisplaying(recyclerView)) {
        //Calling the method getdata again
        getData();
    }
}

}

like image 555
pb007 Avatar asked Nov 13 '17 12:11

pb007


2 Answers

Use this

recyclerView.setOnScrollChangeListener(Fragment1.this);

instead of this

recyclerView.setOnScrollChangeListener(getActivity());

Edit

recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (isLastItemDisplaying(recyclerView)) {
                  //Calling the method getdata again
                   getData();
                }
            }
        });
like image 180
Goku Avatar answered Nov 06 '22 07:11

Goku


Use recyclerView.addOnScrollListener(onScrollListener); instead.

RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
 @Override
 public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
      super.onScrollStateChanged(recyclerView, newState);
 }

 @Override
 public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
      super.onScrolled(recyclerView, dx, dy);
 }
like image 2
Yamini Balakrishnan Avatar answered Nov 06 '22 08:11

Yamini Balakrishnan