here is my code i dont know why its not working now songs is a simple java class which contains getter setters
Before fetching data from JSON i try to statically add data in recycleView and that was working perfectly fine.
Here is code,
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_track, container, false);
myOnClickListener = new track.MyOnClickListener(getActivity());
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerview1);
//recyclerView.setHasFixedSize(true);
layoutManager = new GridLayoutManager(getActivity(), 2);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
loadData();
return view;
}
code of JSON parsing using volley
private void loadData()
{
String url = "http://homejobs.live/mydata.php";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>(){
#Override
public void onResponse(String response) {
try{
JSONArray jsonArray = new JSONArray(response);
Log.d("test", String.valueOf(jsonArray));
Log.d("test", String.valueOf(jsonArray.length()));
for(int i =0 ; i < jsonArray.length() ; i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
songs item = new songs(
jsonObject.getString("id"),
jsonObject.getString("name"),
jsonObject.getString("uri")
);
Log.d("key", String.valueOf(item));
data.add(item);
}
adapter = new recycler_view_adapter(data);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("error"+error);
}
}
);
mRequestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
mRequestQueue.add(stringRequest);
}
recycler_view_adapter class
public class recycler_view_adapter extends RecyclerView.Adapter<recycler_view_adapter.MyViewHolder> {
private ArrayList<songs> dataSet;
public static class MyViewHolder extends RecyclerView.ViewHolder {
public static TextView textViewName;
public static ImageView imageViewIcon;
public MyViewHolder(View itemView) {
super(itemView);
this.textViewName = (TextView) itemView.findViewById(R.id.textView);
this.imageViewIcon = (ImageView) itemView.findViewById(R.id.imageView3);
}
}
public recycler_view_adapter(ArrayList<songs> data) {
this.dataSet = data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card, parent, false);
view.setOnClickListener(track.myOnClickListener);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
Log.d("hy","test");
songs songsData = dataSet.get(position);
MyViewHolder.textViewName.setText(songsData.getName());
System.out.println("hello"+position);
Picasso.get()
.load(songsData.getImage())
.into(MyViewHolder.imageViewIcon);
}
#Override
public int getItemCount()
{
return dataSet.size();
}
}
In your onBindViewHolder, change the following code
MyViewHolder.textViewName.setText(songsData.getName());
System.out.println("hello"+position);
Picasso.get()
.load(songsData.getImage())
.into(MyViewHolder.imageViewIcon);
to the following
holder.textViewName.setText(songsData.getName());
System.out.println("hello"+position);
Picasso.get()
.load(songsData.getImage())
.into(holder.imageViewIcon);
In your code, you are trying to access the textview by using the class name. Instead you should use the holder variable.
Also please check whether you are parsing the json correctly. Check if the
data.add(item);
in the api response is getting executed.
Another suggestion would be to check the size of your dataSet array in the adapter constructor.
Try replacing onBindViewHolder with this
public void onBindViewHolder(final MyViewHolder holder, final int position) {
Log.d("hy","test");
songs songsData = dataSet.get(position);
holder.textViewName.setText(songsData.getName());
System.out.println("hello"+position);
Picasso.get()
.load(songsData.getImage())
.into(holder.imageViewIcon);
}
Related
Here in the given below code, I am trying to display in the image in recyclerview in the imageview after fetching it using picasso, it won't show error or app won't crash either but image won't be displayed, it either shows:
"I/Choreographer: Skipped 30 frames! The application may be doing too much work on its main thread."
Or
W/RecyclerView: No adapter attached; skipping layout
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
LayoutInflater inflater;
List<Lists> lst;
private ItemClickListsner mItemListener;
public Adapter(Context ctx, List<Lists> lst, ItemClickListsner itemClickListsner) {
this.inflater = LayoutInflater.from(ctx);
this.lst = lst;
this.mItemListener = itemClickListsner;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_list, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
// final Lists temp = lst.get(position);
holder.id.setText(lst.get(position).getId());
holder.name.setText(lst.get(position).getName());
holder.prc.setText(lst.get(position).getPrc());
holder.add.setText(lst.get(position).getAddress());
holder.description.setText(lst.get(position).getDes());
holder.park.setText(lst.get(position).getGarage());
holder.net.setText(lst.get(position).getNet());
holder.email.setText(lst.get(position).getMail());
holder.number.setText(lst.get(position).getPnumber());
holder.post.setText(lst.get(position).getTle());
holder.date.setText(lst.get(position).getCrt());
Picasso.with(inflater.getContext())
.load(lst.get(position).getMimage())
.placeholder(R.drawable.bed)
.fit()
.into(holder.ImgView);
holder.itemView.setOnClickListener(view -> {
mItemListener.onItemClick(lst.get(position));
});
}
#Override
public int getItemCount() {
return lst.size();
}
public interface ItemClickListsner{
void onItemClick(Lists lst);
}
public void filterList(ArrayList<Lists> filteredList) {
lst = filteredList;
notifyDataSetChanged();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView id, name, add, prc, description, park, net, post,email,number,date;
ImageView ImgView;
// CardView cardView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
id = itemView.findViewById(R.id.textViewRecy1);
name = itemView.findViewById(R.id.textViewRecy2);
prc = itemView.findViewById(R.id.textViewRecy3);
add = itemView.findViewById((R.id.textViewRecy4));
description = itemView.findViewById(R.id.textViewRecy5);
park = itemView.findViewById(R.id.textViewRecy6);
net = itemView.findViewById(R.id.textViewRecy7);
post = itemView.findViewById(R.id.textViewRecy8);
email = itemView.findViewById(R.id.textViewRecy9);
number = itemView.findViewById(R.id.textViewRecy10);
date = itemView.findViewById(R.id.textViewRecy11);
ImgView = itemView.findViewById(R.id.ImageRecy);
}
}
}
Activity Code
private void extractList() {
RequestQueue queue = Volley.newRequestQueue(this);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, JSON_URL, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
//Log.d("tags", "error: " + jsonObject);
Lists lists = new Lists();
lists.setName(jsonObject.getString("title").toString());
lists.setAddress(jsonObject.getString("location").toString());
lists.setPrc(jsonObject.getString("price").toString());
lists.setDes(jsonObject.getString("description").toString());
lists.setGarage(jsonObject.getString("parking").toString());
lists.setNet(jsonObject.getString("internet").toString());
lists.setMail(jsonObject.getString("email").toString());
lists.setPnumber(jsonObject.getString("phone_number").toString());
lists.setTle(jsonObject.getString("poster").toString());
lists.setCrt(jsonObject.getString("created").toString());
lists.setMimage(jsonObject.getString("photo1").toString());
String p = jsonObject.getString("photo1").toString();
Log.e("kk","msg"+p);
lst.add(lists);
} catch (JSONException e) {
e.printStackTrace();
}
}
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
adapter = new Adapter(getApplicationContext(), lst, new Adapter.ItemClickListsner() {
#Override
public void onItemClick(Lists lst) {
// startActivity(new Intent(HomeActivity.this,roomsDesc.class));
Intent intent = new Intent(HomeActivity.this, roomsDesc.class);
intent.putExtra("title",lst.getName());
intent.putExtra("price",lst.getPrc());
intent.putExtra("location",lst.getAddress());
intent.putExtra("description",lst.getDes());
intent.putExtra("parking",lst.getGarage());
intent.putExtra("internet",lst.getNet());
intent.putExtra("email",lst.getMail());
intent.putExtra("phone_number",lst.getPnumber());
intent.putExtra("poster",lst.getTle());
intent.putExtra("created",lst.getCrt());
intent.putExtra("photo1",lst.getMimage());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
HomeActivity.this.startActivity(intent);
}
});
recyclerView.setAdapter(adapter);
}
I'm creating an app to simply store the records of a tractions and able to see the record.
In IteamListActivity I want to see my records of tractions.
I want to list all the data item in recycle view.
When I click 'View' button in activity_home xml, app crashes.
GitHub Link of the project is Here
Code is
Adapter
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.viewHolder>{
ArrayList<DataModel> list;
Context context;
public DataAdapter(ArrayList<DataModel> list, Context context) {
this.list = list;
this.context = context;
}
#NonNull
#Override
public viewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view =
LayoutInflater.from(context).inflate(R.layout.data_list_design,parent,false);
return new viewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull viewHolder holder, int position) {
DataModel model = list.get(position);
holder.sn.setText(model.getSn());
holder.date.setText(model.getDate());
holder.name.setText(model.getName());
holder.weight.setText(model.getWeight());
holder.rate.setText(model.getRate());
holder.total.setText(model.getTotal());
}
#Override
public int getItemCount() {
return list.size();
}
public class viewHolder extends RecyclerView.ViewHolder {
TextView sn,date,name,weight,rate,total;
public viewHolder(#NonNull View itemView) {
super(itemView);
sn = itemView.findViewById(R.id.snTitle);
date = itemView.findViewById(R.id.dateTitle);
name = itemView.findViewById(R.id.nameTitle);
weight = itemView.findViewById(R.id.weightTitle);
rate = itemView.findViewById(R.id.rateTitle);
total = itemView.findViewById(R.id.totalTitle);
}
}
}
HomeActivity
binding.listview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(HomeActivity.this,ItemListActivity.class );
startActivity(intent);
}
});
ItemListActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityItemListBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
ArrayList<DataModel> list = new ArrayList<>();
list.add(new DataModel(1,"2021-07-29","Potato", 76,50,100));
list.add(new DataModel(2,"2021-07-30","Potato", 106,60,100));
list.add(new DataModel(3,"2021-08-02","Potato", 83,80,100));
list.add(new DataModel(4,"2021-08-03","Potato", 67,90,100));
list.add(new DataModel(5,"2021-08-05","Potato", 70,70,100));
DataAdapter adapter = new DataAdapter(list,this);
LinearLayoutManager linearLayoutManager = new
LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
binding.datalistRv.setLayoutManager(linearLayoutManager);
binding.datalistRv.setNestedScrollingEnabled(false);
binding.datalistRv.setAdapter(adapter);
}
Solution is
#Override
public void onBindViewHolder(#NonNull viewHolder holder, int position) {
DataModel model = list.get(position);
holder.sn.setText(model.getSn().toString());
holder.date.setText(model.getDate());
holder.name.setText(model.getName());
holder.weight.setText(model.getWeight().toString());
holder.rate.setText(model.getRate().toString());
holder.total.setText(model.getTotal().toString());
}
Reason of crush is model.getSn(), model.getWeight(), model.getRate(), model.getTotal() return Integer and textView.setText() calls public final void setText(#StringRes int resid) which tries to find string by Integers which you provided from your model.
I was trying to make a chat app for the android, so I used RecyclerView for it. I have a problem for the adapter, my chat room's displaying blank for the JSON response they get. Did I miss something on my code?
Here is my adapter class
public class PesanRecycleAdapter extends RecyclerView.Adapter<PesanRecycleAdapter.ViewHolder> {
private String username;
private Context context;
private int SELF = 786;
private ArrayList<Pesan> pesan;
public PesanRecycleAdapter(Context context, ArrayList<Pesan> pesan, String username){
this.username = username;
this.pesan = pesan;
this.context = context;
}
#Override
public int getItemViewType(int position) {
Pesan psn = pesan.get(position);
if (psn.getUsernameFrom() == username) {
return SELF;
}
return position;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView;
if (viewType == SELF) {
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.chat_thread_me, parent, false);
} else {
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.chat_thread_other, parent, false);
}
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Pesan psn = pesan.get(position);
holder.textViewMessage.setText(psn.getPesan());
holder.textViewTime.setText(psn.getSentAt());
}
#Override
public int getItemCount() {
return pesan.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView textViewMessage;
public TextView textViewTime;
public ViewHolder(View itemView) {
super(itemView);
textViewMessage = (TextView) itemView.findViewById(R.id.textViewMessage);
textViewTime = (TextView) itemView.findViewById(R.id.textViewTime);
}
}
}
Any help or suggestion is welcome
And here where I used that adapter on activity
public void getpesan() {
try {
apiservice.get_pesan(username, "ahnafgg").enqueue(new Callback<ResponPesan>() {
#Override
public void onResponse(Call<ResponPesan> call, Response<ResponPesan> response) {
Log.d(TAG, "onResponse: response..."+response);
dummyData = response.body().getPesan();
createRecycleView();
}
#Override
public void onFailure(Call<ResponPesan> call, Throwable t) {
Log.d(TAG, "onFailure: response...");
Toast.makeText(RuangPesan.this,"Gagal ambil chat",Toast.LENGTH_SHORT).show();
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void createRecycleView(){
adapter = new PesanRecycleAdapter(RuangPesan.this, pesan, username);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
Log.d(TAG, "********************************");
scrollToBottom();
}
Probably you forgot to set date in the model before initialising recycler view
Use the following way from your activity class:
initData(); //Do this first
RecyclerView recyclerView = findViewById(R.id.recyclerview);
Context context = MainActivity.this;
PesanRecycleAdapter pesanRecycleAdapter = new PesanRecycleAdapter(context, list,"Fahad");
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(pesanRecycleAdapter);
I think everything is okay here, maybe you forgot setting layoutManager for recyclerView or notify adapter after setting data
When I just display string data it seems to show up fine, but when I try to display an int or double the RecyclerView won't populate. I am pulling from the Google places API JSON. I think maybe it is the way I'm using my onBindViewHolder()? Thanks
// MainActivity
private void getJson() {
String URL = https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=40.7085,-74.003124&opennow&radius=5000&type=restaurant&key=
JsonObjectRequest root = new JsonObjectRequest(Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray results = response.getJSONArray("results");
Log.d("RESULTS", String.valueOf(results));
for(int i = 0; i<results.length(); i++) {
JSONObject resultsObj = results.getJSONObject(i);
mImageUrls.add(resultsObj.getString("icon"));
mTitle.add(resultsObj.getString("name"));
//mRating.add(resultsObj.getDouble("rating"));
mPriceLevel.add(resultsObj.getInt("price_level"));
}
getRecyclerView();
} catch (JSONException e) {
e.printStackTrace();
}
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
mRequestQueue.add(root);
}
private void getRecyclerView() {
// LinearLayoutManager
recyclerView = findViewById(R.id.recyclerView);
adapter = new RecyclerViewAdapter(mImageUrls, mTitle, mPriceLevel, this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
}
And the RecyclerViewAdapter Class is.
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
private static final String TAG = "RecyclerViewAdapter";
private ArrayList<String> rNames = new ArrayList<>();
private ArrayList<String> rImageUrls = new ArrayList<>();
private ArrayList<Double> rRatings = new ArrayList<>();
private ArrayList<Integer> rPriceLevel = new ArrayList<>();
private Context mContext;
public RecyclerViewAdapter(ArrayList<String> image, ArrayList<String> name, ArrayList<Integer> priceLevel, Context context) {//, ArrayList<Double> rating
this.rImageUrls = image;
this.rNames = name;
//this.rRatings = rating;
this.rPriceLevel = priceLevel;
mContext = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_item, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
//return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
Glide.with(mContext).asBitmap().load(rImageUrls.get(position)).into(holder.image);
holder.name.setText(rNames.get(position));
//holder.rating.setText(rRatings.get(position));
holder.priceLevel.setText(rPriceLevel.get(position));
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: clicked on an image: " + rNames.get(position));
Toast.makeText(mContext, rNames.get(position), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return rNames.size(); //we can use rImageUrls/rRatings as well because they are all the same size
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView image;
TextView name;
TextView rating;
TextView priceLevel;
TextView address;
RelativeLayout parentLayout;
public ViewHolder(View itemView) {
super(itemView);
image = (ImageView) itemView.findViewById(R.id.image);
name = (TextView) itemView.findViewById(R.id.title);
//rating = itemView.findViewById(R.id.rating);
priceLevel = (TextView) itemView.findViewById(R.id.priceLevel);
parentLayout = itemView.findViewById(R.id.parentLayout);
}
}
}
The reason for this is you are not converting Double to String
change this line holder.rating.setText(rRatings.get(position)); to holder.rating.setText(String.valueOf(rRatings.get(position)));
I would like to suggest you to create an object having all necessary parameters in it and then pass a single list of that object to the RecyclerViewAdapter.
public class MapElement {
public String name;
public String imageUrl;
public Double rating;
public Integer price;
}
Then create an ArrayList of this object when you get the response from your getJson function call. Now in your adapter just use a single list of MapElement object to show the data from there.
The modified adapter should look like this.
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
private static final String TAG = "RecyclerViewAdapter";
private ArrayList<MapElement> elements = new ArrayList<>();
private Context mContext;
public RecyclerViewAdapter(ArrayList<MapElement> elements, Context context) {
this.elements = elements;
mContext = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_item, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
Glide.with(mContext).asBitmap().load(rImageUrls.get(position)).into(holder.image);
holder.name.setText(elements.get(position).name);
holder.rating.setText(elements.get(position).rating);
holder.priceLevel.setText(elements.get(position).price);
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: clicked on an image: " + rNames.get(position));
Toast.makeText(mContext, elements.get(position).name, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return elements.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView image;
TextView name;
TextView rating;
TextView priceLevel;
TextView address;
RelativeLayout parentLayout;
public ViewHolder(View itemView) {
super(itemView);
image = (ImageView) itemView.findViewById(R.id.image);
name = (TextView) itemView.findViewById(R.id.title);
rating = itemView.findViewById(R.id.rating);
priceLevel = (TextView) itemView.findViewById(R.id.priceLevel);
parentLayout = itemView.findViewById(R.id.parentLayout);
}
}
}
First you should check that the rating you are getting is a double value.
It might be the case that an exception is thrown after this line
mRating.add(resultsObj.getDouble("rating"))
Also as #hooray_todd siggested textview only takes string value so you have to change your data into string.
i want know how to scroll to get more data on my recycler view
example my using wordpress api to have 10post from my website
and i want to get 5 per load in recycler and scroll more to get 5 post more
but i don't know how to coding please than a look and give me some correct idea !!
News_list.java
/**
* A simple {#link Fragment} subclass.
*/
public class News_List extends Fragment {
private static final String URL = "https://chsknews.com/wp-json/wp/v2/posts/";
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<News_Item> news_itemList;
private SwipeRefreshLayout swipeRefreshLayout;
public News_List() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_news__list, container, false);
swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_refresh);
recyclerView = (RecyclerView) rootView.findViewById(R.id.MRecyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
news_itemList = new ArrayList<>();
News_Loader();
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
News_Loader();
Toast.makeText(getContext(),"ដំណើរការជោគជ័យក្នុងការទាញយកពត៏មានចុងក្រោយ",Toast.LENGTH_SHORT).show();
news_itemList.clear();
}
});
return rootView;
}
private void News_Loader() {
final ProgressDialog progressDialog = new ProgressDialog(getContext());
progressDialog.setMessage("Loading News");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET,
URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
//JSONObject jsonObject = new JSONObject(response);
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++){
JSONObject o = array.getJSONObject(i);
// Log.v("ID",o.getJSONObject("content").optString("rendered"));
news_itemList.add(new News_Item(
o.getJSONObject("title").getString("rendered"),
o.getString("date"),
o.getJSONObject("better_featured_image").getString("source_url"),
o.getString("date"),
o.getJSONObject("content").getString("rendered"))
);
// news_itemList.add(news_item);
}
adapter = new CustomAdapter(news_itemList,getContext());
recyclerView.setAdapter(adapter);
if (swipeRefreshLayout.isRefreshing())
{
swipeRefreshLayout.setRefreshing(false);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getContext(), error.getMessage(),Toast.LENGTH_LONG).show();
if (swipeRefreshLayout.isRefreshing())
{
swipeRefreshLayout.setRefreshing(false);
}
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(stringRequest);
}
}
Adapter Class
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
private List<News_Item> news_items;
private Context context;
public CustomAdapter(List<News_Item> news_items, Context context) {
this.news_items = news_items;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view,parent,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final News_Item news_item = news_items.get(position);
holder.title.setText(Html.fromHtml(news_item.getTitle()));
holder.news_date.setText((news_item.getNews_date()));
Picasso.with(context)
.load(news_item.getImage_url())
.fit()
.into(holder.news_img);
holder.news_img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,News_Single_Post.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra("source_url",news_items.get(position).getImage_url());
intent.putExtra("rendered", news_items.get(position).getTitle());
intent.putExtra("date",news_items.get(position).getNews_date());
intent.putExtra("content",news_items.get(position).getNews_content());
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return news_items.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView title;
public TextView news_date;
public ImageView news_img;
public ViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.news_title);
news_date = (TextView) itemView.findViewById(R.id.news_date);
news_img = (ImageView) itemView.findViewById(R.id.news_image);
}
}
}
private boolean loading = true;
int pastVisiblesItems, visibleItemCount, totalItemCount;
mRecyclerView.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;
Log.v("...", "Last Item Wow !");
//Do pagination.. i.e. fetch new data
}
}
}
}
});
Don't forget to add
LinearLayoutManager mLayoutManager;
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);