This is my LatestGradeAdapter
public class LatestGradeAdapter extends RecyclerView.Adapter<LatestGradeAdapter.RecyclerViewHolder> {
private Context mCtx;
private List<ListGradeData> sectionList;
public LatestGradeAdapter(Context mCtx, List<ListGradeData> sectionList) {
this.mCtx = mCtx;
this.sectionList = sectionList;
}
#NonNull
#Override
public RecyclerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.section_data_list, parent, false);
return new LatestGradeAdapter.RecyclerViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewHolder holder, int position) {
final ListGradeData sections = sectionList.get(position);
//BIND DATA
holder.textViewSection.setText(sections.getSection());
holder.textViewLevel.setText(sections.getLevel());
holder.textViewSchoolYear.setText(sections.getSchoolyear());
}
#Override
public int getItemCount() {
return sectionList.size();
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder {
//Variables for list
TextView textViewSection, textViewLevel, textViewSchoolYear;
//Variables for head section
TextView textHeaderSection, textHeaderLevel, textHeaderSchoolYear;
public RecyclerViewHolder(final View itemView) {
super(itemView);
textViewSection = (TextView) itemView.findViewById(R.id.textSection);
textViewLevel = (TextView) itemView.findViewById(R.id.textLevel);
textViewSchoolYear = (TextView) itemView.findViewById(R.id.textYear);
}
}
}`
This is my LatestGradeFragment
`public class LatestGradeFragment extends Fragment {
List<ListGradeData> sectionList;
RecyclerView recyclerView;
public static LatestGradeFragment newInstance() {
return new LatestGradeFragment();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_latest_grade, container, false);
//RecyclerView+CardView for section
recyclerView = (RecyclerView) rootView.findViewById(R.id.display_recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
sectionList = new ArrayList<>();
loadSection();
return rootView;
}
private void loadSection() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, Constants.USER_GRADE,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting product object from json array
JSONObject sections = array.getJSONObject(i);
//adding the product to product list
sectionList.add(new ListGradeData(
sections.getInt("id"),
sections.getString("section"),
sections.getString("level"),
sections.getString("schoolyear")
));
}
//creating adapter object and setting it to recyclerview
LatestGradeAdapter adapter = new LatestGradeAdapter(getActivity(), sectionList);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(getActivity().getApplicationContext()).add(stringRequest);
}
#Override
public String toString() {
return "HomeFragment";
}
}`
I tried everything what I've searched for and when I apply it, it doesn't work.
could anyone help me?
private boolean loading = true;
private int pastVisiblesItems, visibleItemCount, totalItemCount;
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if(dy > 0) //check for scroll down{
visibleItemCount = mLayoutManager.getChildCount();
totalItemCount = mLayoutManager.getItemCount();
pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();
if (loading) {
if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) {
loading = false;
loadSection();
}
}
}
}
});
Related
I am implementing pagination in recyclerview on scroll. I am fetching data from JSON API. Below is the code of Fragment Class. 1st page is loading successfully in recyclerview, but when I scroll to bottom 2nd page is not loading and throws the following error:
java.lang.IndexOutOfBoundsException: Index: 10, Size: 10
This is my Fragment Class:
public class LeadsFragment extends Fragment {
RecyclerView recyclerView;
LeadsAdapter leadsAdapter;
List<LeadModel> rowsArrayList = new ArrayList<>();
private LinearLayoutManager layoutManager;
Toolbar toolbar;
private int page = 1;
private int totalItemCount;
private int firstVisibleItem;
private int visibleItemCount;
private int previousTotal;
private boolean isLoad=true;
String url;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_leads, container, false);
toolbar = view.findViewById(R.id.toolbar);
( (AppCompatActivity) getActivity() ).setSupportActionBar(toolbar);
( (AppCompatActivity) getActivity() ).getSupportActionBar().setTitle("");
url = "myurl?page="+page;
recyclerView = view.findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
leadsAdapter = new LeadsAdapter(getContext(), rowsArrayList, recyclerView);
recyclerView.setAdapter(leadsAdapter);
getAPIData();
pagination();
return view;
}
private void getAPIData() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
LeadModel leadModelList = gson.fromJson(response, LeadModel.class);
for (int i = 0; i < leadModelList.getData().size(); i++) {
rowsArrayList.add(leadModelList);
}
leadsAdapter.setItems(rowsArrayList);
leadsAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), error.toString(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue queue = Volley.newRequestQueue(getContext());
queue.add(stringRequest);
}
private void pagination() {
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(#NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
#Override
public void onScrolled(#NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (dy > 0) {
visibleItemCount = layoutManager.getChildCount();
totalItemCount = layoutManager.getItemCount();
firstVisibleItem = layoutManager.findFirstVisibleItemPosition();
Log.e("visibleItemCount", "." + visibleItemCount);
Log.e("totalItemCount", "." + totalItemCount);
Log.e("firstVisibleItem", "." + firstVisibleItem);
if (isLoad) {
if (totalItemCount > previousTotal) {
previousTotal = totalItemCount;
page++;
isLoad = false;
Log.e("previousTotal", "." + previousTotal);
Log.e("Pageeeee", "." + page);
}
}
if (!isLoad && ( firstVisibleItem + visibleItemCount ) >= totalItemCount) {
Log.e("Checking", "." + page);
getAPIData();
isLoad = true;
}
}
}
});
}
}
My Adapter Class:
public class LeadsAdapter extends RecyclerView.Adapter<LeadsAdapter.ViewHolder> {
Context context;
List<LeadModel> leadsModelList;
LeadsMeta leadsMetaList;
RecyclerView recyclerView;
final View.OnClickListener onClickListener = new MyOnClickListener();
public LeadsAdapter(Context context, List<LeadModel> leadsModelList, RecyclerView recyclerView) {
this.context = context;
this.leadsModelList = leadsModelList;
this.recyclerView = recyclerView;
}
public void setItems(List<LeadModel> leadsModelList) {
this.leadsModelList= new ArrayList<>(leadsModelList);
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView name, topic, sub_topic, city, credits, quotes;
public ViewHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.tvName);
topic = itemView.findViewById(R.id.tvTopic);
sub_topic = itemView.findViewById(R.id.tvSubTopic);
city = itemView.findViewById(R.id.tvLocation);
credits = itemView.findViewById(R.id.tvCredits);
quotes = itemView.findViewById(R.id.tvQuotes);
}
}
#NonNull
#Override
public LeadsAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.lead_card, viewGroup, false);
view.setOnClickListener(onClickListener);
LeadsAdapter.ViewHolder viewHolder = new LeadsAdapter.ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull LeadsAdapter.ViewHolder viewHolder, int position) {
LeadModel leadsModel = leadsModelList.get(position);
viewHolder.name.setText(leadsModel.getData().get(position).getName());
}
#Override
public int getItemCount() {
return leadsModelList.size();
}
}
Whenever calling getApi method sends new response and adding data again to the list, but that list not sent to adapter to update new list.
Instead of like this
leadsAdapter = new LeadsAdapter(getContext(), rowsArrayList, recyclerView);
Create a method in adapter with list as a parameter and pass the arraylist to method and notify when new data response.
I have a problem with Recyclerview load more items. First fetch data work perfectly. Added onScrolled method, added offset to request. try to display 10 records at a time (increase offset by 10 in each request and set limit on 10 by starting with offset 0 and increasing it each time when bottom is reached. Every request should return next 10 items). Please check my below code.
PersonUtils.java
public class PersonUtils {
private String personFirstName;
private String jobProfile;
public String getPersonFirstName() {
return personFirstName;
}
public void setPersonFirstName(String personFirstName) {
this.personFirstName = personFirstName;
}
public String getJobProfile() {
return jobProfile;
}
public void setJobProfile(String jobProfile) {
this.jobProfile = jobProfile;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.Adapter mAdapter;
RecyclerView.LayoutManager layoutManager;
List<PersonUtils> personUtilsList;
RequestQueue rq;
String request_url = "https://next.json-generator.com/api/json/get/Vkg6e6Vcu";
String url = "https://.../api/json/offset=";
static int total = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rq = Volley.newRequestQueue(this);
recyclerView = (RecyclerView) findViewById(R.id.recycleViewContainer);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
personUtilsList = new ArrayList<>();
sendRequest(request_url);
// sendRequest(url, 0);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(#NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
System.out.print("test");
if(dx>0){
}
if(dy>0){
total = total+10;
System.out.print("testing");
// sendRequest(url, total);
sendRequest(request_url);
}
}
});
}
// public void sendRequest(String request_url, int offsetIndex){
public void sendRequest(String request_url){
// request_url = request_url+offsetIndex;
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, request_url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for(int i = 0; i < response.length(); i++){
PersonUtils personUtils = new PersonUtils();
try {
JSONObject jsonObject = response.getJSONObject(i);
personUtils.setPersonFirstName(jsonObject.getString("name"));
personUtils.setJobProfile(jsonObject.getString("id"));
} catch (JSONException e) {
e.printStackTrace();
}
personUtilsList.add(personUtils);
}
mAdapter = new CustomRecyclerAdapter(MainActivity.this, personUtilsList);
recyclerView.setAdapter(mAdapter);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("Volley Error: ", error.getMessage());
}
});
rq.add(jsonArrayRequest);
}
}
CustomRecyclerAdapter.java
public class CustomRecyclerAdapter extends RecyclerView.Adapter<CustomRecyclerAdapter.ViewHolder> {
private Context context;
private List<PersonUtils> personUtils;
public CustomRecyclerAdapter(Context context, List personUtils) {
this.context = context;
this.personUtils = personUtils;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.itemView.setTag(personUtils.get(position));
PersonUtils pu = personUtils.get(position);
holder.pName.setText(pu.getPersonFirstName());
holder.pJobProfile.setText(pu.getJobProfile());
}
#Override
public int getItemCount() {
return personUtils.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView pName;
public TextView pJobProfile;
public ViewHolder(View itemView) {
super(itemView);
pName = (TextView) itemView.findViewById(R.id.pNametxt);
pJobProfile = (TextView) itemView.findViewById(R.id.pJobProfiletxt);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PersonUtils cpu = (PersonUtils) view.getTag();
Toast.makeText(view.getContext(), cpu.getPersonFirstName()+" "+" is "+ cpu.getJobProfile(), Toast.LENGTH_SHORT).show();
}
});
}
}
}
Required Output:
on loading call sendRequest(String request_url, int offsetIndex)
if user scroll then call sendRequest(String request_url, int offsetIndex)
Every request should return next 10 items
I have to display 100 data on recycler-view. so I want to implement load more to make it efficient. when I tried to compile the code, the progress bar doesn't go and it leaves big space on the bottom. and it just loaded 20 data not all of them.
this is the code for my adapter
class LoadingViewHolder extends RecyclerView.ViewHolder{
public ProgressBar progressBar;
public LoadingViewHolder(#NonNull View itemView) {
super(itemView);
progressBar=(ProgressBar) itemView.findViewById(R.id.loadmore);
}
}
class herbalViewHolder extends RecyclerView.ViewHolder{
TextView namaHerbal,khasiatHerbal;
ImageView thumbnail;
public herbalViewHolder(#NonNull View itemView) {
super(itemView);
namaHerbal = itemView.findViewById(R.id.nama_herbal);
khasiatHerbal = itemView.findViewById(R.id.khasiat_herbal);
thumbnail = itemView.findViewById(R.id.gambar_herbal);
}
}
public class herbalAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private final int VIEW_TYPE_ITEM=0,VIEW_TYPE_LOADING=1;
private loadMore loadMore;
boolean isLoading;
private Context mCtx;
List<herbalModel> herbalModelList;
int visibleThreshold=5;
int lastVisibleItem,totalItemCount;
public herbalAdapter(RecyclerView recyclerView,Context mCtx, List<herbalModel> herbalModelList) {
this.mCtx = mCtx;
this.herbalModelList = herbalModelList;
final LinearLayoutManager linearLayoutManager = (LinearLayoutManager)recyclerView.getLayoutManager();
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(#NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
totalItemCount = linearLayoutManager.getItemCount();
lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
if (!isLoading && totalItemCount <= (lastVisibleItem+visibleThreshold))
{
if (loadMore != null)
loadMore.onLoadMore();
isLoading=true;
}
}
});
}
#Override
public int getItemViewType(int position) {
return herbalModelList.get(position) == null ? VIEW_TYPE_LOADING:VIEW_TYPE_ITEM;
}
public void setLoadMore(loadMore loadMore) {
this.loadMore = loadMore;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
if(i == VIEW_TYPE_ITEM)
{
CardView v = (CardView) LayoutInflater.from(parent.getContext())
.inflate(R.layout.cardview_herbal, parent,false);
// View view =inflater.inflate(R.layout.cardview_herbal,null);
return new herbalViewHolder(v);
}
else if(i == VIEW_TYPE_LOADING)
{
View view = LayoutInflater.from(mCtx).inflate(R.layout.item_loading,parent,false);
return new LoadingViewHolder(view);
}
return null;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder viewHolder, int i) {
if (viewHolder instanceof herbalViewHolder)
{
herbalModel detailherbal =herbalModelList.get(i);
herbalViewHolder herbalViewHolder = (herbalViewHolder) viewHolder;
herbalViewHolder.namaHerbal.setText(detailherbal.getNama());
herbalViewHolder.khasiatHerbal.setText(detailherbal.getKhasiat());
Glide.with(mCtx)
.load(detailherbal.getThumbnail())
.into(herbalViewHolder.thumbnail);
final String idHerbal =detailherbal.getId();
herbalViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(mCtx, detailHerbal.class);
i.putExtra("idHerbal", idHerbal);
mCtx.startActivity(i);
}
});
}
else if(viewHolder instanceof LoadingViewHolder)
{
LoadingViewHolder loadingViewHolder = (LoadingViewHolder) viewHolder;
loadingViewHolder.progressBar.setIndeterminate(true);
}
}
#Override
public int getItemCount() {
return herbalModelList.size();
}
public void setLoaded() {
isLoading = false;
}
public void filterlist (ArrayList<herbalModel> filteredList)
{
herbalModelList =filteredList;
notifyDataSetChanged();
}
}
this is the main activity for displaying recyclerview
private void get10Data() {
String url ="https://jsonplaceholder.typicode.com/photos";
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.d(TAG,"Onresponse"+jsonArray.toString());
for(int i = 0; i < 10; i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.d(TAG,"jsonobject"+jsonObject);
herbalModels.add(
new herbalModel(
jsonObject.getString("title"),
"Khasiat",
jsonObject.getString("albumId"),
jsonObject.getString("id"),
jsonObject.getString("thumbnailUrl")
)
);
}
catch(JSONException e) {
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d(TAG,"Onerror"+volleyError.toString());
}
});
MySingleton.getInstance(getActivity()).addToRequestQueue(request);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_herbal, container, false);
herbalModels = new ArrayList<>();
RequestQueue queue = MySingleton.getInstance(this.getActivity().getApplicationContext()).getRequestQueue();
get10Data();
sortData(rootView);
StartRecyclerView(rootView);
return rootView ;
}
private void StartRecyclerView(View rootView) {
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview_herbal);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new herbalAdapter(recyclerView,getActivity(),herbalModels);
recyclerView.setAdapter(adapter);
//set loaded more event
adapter.setLoadMore(new loadMore() {
#Override
public void onLoadMore() {
if (herbalModels.size() <= 20)
{
herbalModels.add(null);
adapter.notifyItemInserted(herbalModels.size()-1);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
herbalModels.remove(herbalModels.size()-1);
adapter.notifyItemRemoved(herbalModels.size());
final int index = herbalModels.size();
final int end = index+10;
String url ="https://jsonplaceholder.typicode.com/photos";
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.d(TAG,"Onresponse"+jsonArray.toString());
for(int i = index; i < end; i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.d(TAG,"jsonobject"+jsonObject);
herbalModels.add(
new herbalModel(
jsonObject.getString("title"),
"Khasiat",
jsonObject.getString("albumId"),
jsonObject.getString("id"),
jsonObject.getString("thumbnailUrl")
)
);
}
catch(JSONException e) {
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d(TAG,"Onerror"+volleyError.toString());
}
});
MySingleton.getInstance(getActivity()).addToRequestQueue(request);
adapter.notifyDataSetChanged();
adapter.setLoaded();
}
},5000);
}
}
});
}
I'm trying to add a load more.
I tried to apply what I'd search and it doesn't work.
here's my code.
LatestGradeFragment
public class LatestGradeFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener{
List<ListGradeData> sectionList;
RecyclerView recyclerView;
SwipeRefreshLayout mSwipeRefreshLayout;
public static LatestGradeFragment newInstance() {
return new LatestGradeFragment();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_latest_grade, container, false);
//RecyclerView+CardView for section
recyclerView = (RecyclerView) rootView.findViewById(R.id.display_recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
sectionList = new ArrayList<>();
mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipeRefreshSection);
mSwipeRefreshLayout.setOnRefreshListener(this);
mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary,
android.R.color.holo_green_dark,
android.R.color.holo_orange_dark,
android.R.color.holo_blue_dark);
mSwipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
mSwipeRefreshLayout.setRefreshing(true);
// Fetching data from server
loadSection();
}
});
return rootView;
}
#Override
public void onRefresh() {
loadSection();
}
private void loadSection() {
mSwipeRefreshLayout.setRefreshing(true);
StringRequest stringRequest = new StringRequest(Request.Method.GET, Constants.USER_GRADE,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
if(sectionList!=null) {
sectionList.clear();
}
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting product object from json array
JSONObject sections = array.getJSONObject(i);
//adding the product to product list
sectionList.add(new ListGradeData(
sections.getInt("id"),
sections.getString("section"),
sections.getString("level"),
sections.getString("schoolyear")
));
}
//creating adapter object and setting it to recyclerview
LatestGradeAdapter adapter = new LatestGradeAdapter(getActivity(), sectionList);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
// Stopping swipe refresh
mSwipeRefreshLayout.setRefreshing(false);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Stopping swipe refresh
mSwipeRefreshLayout.setRefreshing(false);
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(getActivity().getApplicationContext()).add(stringRequest);
}
#Override
public String toString() {
return "LatestGradeFragment";
}
}`
and here's my LatestGradeAdapter:
public class LatestGradeAdapter extends RecyclerView.Adapter<LatestGradeAdapter.RecyclerViewHolder> {
private Context mCtx;
private List<ListGradeData> sectionList;
`public LatestGradeAdapter(Context mCtx, List<ListGradeData> sectionList) {
this.mCtx = mCtx;
this.sectionList = sectionList;
}
#NonNull
#Override
public RecyclerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.section_data_list, parent, false);
return new LatestGradeAdapter.RecyclerViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewHolder holder, int position) {
final ListGradeData sections = sectionList.get(position);
//BIND DATA
holder.textViewSection.setText(sections.getSection());
holder.textViewLevel.setText(sections.getLevel());
holder.textViewSchoolYear.setText(sections.getSchoolyear());
}
#Override
public int getItemCount() {
return sectionList.size();
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder {
//Variables for list
TextView textViewSection, textViewLevel, textViewSchoolYear;
//Variables for head section
TextView textHeaderSection, textHeaderLevel, textHeaderSchoolYear;
public RecyclerViewHolder(final View itemView) {
super(itemView);
textViewSection = (TextView) itemView.findViewById(R.id.textSection);
textViewLevel = (TextView) itemView.findViewById(R.id.textLevel);
textViewSchoolYear = (TextView) itemView.findViewById(R.id.textYear);
}
}
}`
Add this code in your LatestGradeFragment.class
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
int lastVisiblePosition = layoutManager.findLastVisibleItemPosition();
if (lastVisiblePosition == recyclerView.getChildCount()) {
progrssBar.setVisibility(View.VISIBLE);
loadMore(); //This methos is used for load next set of items.
}
}
});
public void loadMore(){
//load next set of items to adapter
adapter.notifyDataSetChanged();
progrssBar.setVisibility(View.GONE);
}
Create your fragment_latest_grade like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/progressBar" />
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerInParent="true"
android:visibility="gone" />
</RelativeLayout>
Main activty.java
i am using volley library.
here i am trying to do is load 10 images on Card views until user reach at the end
public class MainActivity extends ActionBarActivity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
String loginURL="http://*****o.comli.com/rimgid.php";
RequestQueue requestQueue;
String[] title=null,url=null;
int i=0;
Activity activity= MainActivity.this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this);
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
requestQueue = Volley.newRequestQueue(this);
//output = (TextView) findViewById(R.id.hi);
JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, loginURL,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try{
JSONArray ja = response.getJSONArray("hi");//parsing id and image url
title=new String[ja.length()];
url=new String[ja.length()];
for(int i=0; i < ja.length(); i++){
JSONObject jsonObject = ja.getJSONObject(i);
// int id = Integer.parseInt(jsonObject.optString("id").toString());
url[i] ="http://developer.andrinfo.comli.com/img/"+ jsonObject.getInt("id")+".jpg";
title[i] = jsonObject.getString("name");
}
mAdapter = new MyRecyclerViewAdapter(activity,getDataSet(url,title,ja.length()));
mRecyclerView.setAdapter(mAdapter);
// Toast.makeText(getApplicationContext(),url[2],Toast.LENGTH_SHORT).show();
//output.setText(data);
}catch(JSONException e){e.printStackTrace();}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley",error.toString());
}
}
);
requestQueue.add(jor);
//requestQueue.start();
// Code to Add an item with default animation
//((MyRecyclerViewAdapter) mAdapter).addItem(obj, index);
// Code to remove an item with default animation
//((MyRecyclerViewAdapter) mAdapter).deleteItem(index);
}
private ArrayList<DataObject> getDataSet(String[] images,String[] headlines,int size) {
// String[] images = getResources().getStringArray(R.array.images_array);
//String[] headlines = getResources().getStringArray(R.array.headline_array);
ArrayList results = new ArrayList<DataObject>();
for (int index = 0; index < size; index++) {
DataObject obj = new DataObject(headlines[index],
"Secondary " + index);
obj.setUrl(images[index]);
//obj.setHeadline(headlines[index]);
results.add(index, obj);
}
return results;
}
}
my adapter class
public class MyRecyclerViewAdapter extends RecyclerView
.Adapter<MyRecyclerViewAdapter
.DataObjectHolder> {
private static String LOG_TAG = "MyRecyclerViewAdapter";
private ArrayList<DataObject> mDataset;
private static MyClickListener myClickListener;
private String headline;
private String reporterName;
private String date;
private String url;
private Activity activityContext;
public static class DataObjectHolder extends RecyclerView.ViewHolder
{
TextView label;
TextView dateTime;
ImageView imageView;
public DataObjectHolder(View itemView) {
super(itemView);
label = (TextView) itemView.findViewById(R.id.textView);
dateTime = (TextView) itemView.findViewById(R.id.textView2);
imageView=(ImageView)itemView.findViewById(R.id.imageView);
Log.i(LOG_TAG, "Adding Listener");
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
public MyRecyclerViewAdapter(Activity context,ArrayList<DataObject> myDataset) {
mDataset = myDataset;
activityContext=context;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cardview, parent, false);
DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return dataObjectHolder;
}
#Override
public void onBindViewHolder(DataObjectHolder holder, int position) {
Context context=null;
holder.label.setText(mDataset.get(position).getmText1());
holder.dateTime.setText(mDataset.get(position).getmText2());
Drawable placeholder = holder.imageView.getContext().getResources().getDrawable(R.drawable.placeholder);
holder.imageView.setImageDrawable(placeholder);
//new ImageDownloaderTask(holder.imageView).execute(mDataset.get(position).getUrl());
Picasso.with(activityContext)
.load(mDataset.get(position).getUrl())
.placeholder(R.drawable.placeholder)
.into(holder.imageView);
}
public void addItem(DataObject dataObj, int index) {
mDataset.add(index, dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mDataset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return mDataset.size();
}
public interface MyClickListener {
public void onItemClick(int position, View v);
}
}
please help me to do this.
I want to use the scroll listener with the main activity..
I use this class to implement endless scrolling behaviour on RecyclerViews
public abstract class EndlessRecyclerOnScrollListener extends RecyclerView.OnScrollListener {
public static String TAG = EndlessRecyclerOnScrollListener.class.getSimpleName();
private int previousTotal = 0; // The total number of items in the dataset after the last load
private boolean loading = true; // True if we are still waiting for the last set of data to load.
private int visibleThreshold = 5; // The minimum amount of items to have below your current scroll position before loading more.
int firstVisibleItem, visibleItemCount, totalItemCount;
private int current_page = 1;
private LinearLayoutManager mLinearLayoutManager;
public EndlessRecyclerOnScrollListener(LinearLayoutManager linearLayoutManager) {
this.mLinearLayoutManager = linearLayoutManager;
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
visibleItemCount = recyclerView.getChildCount();
totalItemCount = mLinearLayoutManager.getItemCount();
firstVisibleItem = mLinearLayoutManager.findFirstVisibleItemPosition();
if (loading) {
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
}
}
if (!loading && (totalItemCount - visibleItemCount)
<= (firstVisibleItem + visibleThreshold)) {
// End has been reached
// Do something
current_page++;
onLoadMore(current_page);
loading = true;
}
}
public abstract void onLoadMore(int current_page);
}
Use it like this:
mRecyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(layoutManager) {
#Override
public void onLoadMore(int current_page) {
//call server
getRestaurantReviews(current_page);
}
});