hi guys i have a card view that populate it's data from a json. I parse json with volley and it is successfull .
but in card view there is nothing to show
here is my json
{"photo":[{"id":"4","profile_id":"mahdi","caption":"hello","image_url":"https:\/\/hemispheric-suggest.000webhostapp.com\/img\/img\/birjand.jpg","profile_img_url":"https:\/\/hemispheric-suggest.000webhostapp.com\/prof\/prof\/prof_1.jpg","insert_time":"2017-07-09 11:21:44"}
and my fragment adapter :
private RecyclerView recyclerView;
private RequestQueue mRequestQueue;
ArrayList<Card> list = new ArrayList<>();
String url = "My url";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag,container,false);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler);
mRequestQueue = Volley.newRequestQueue(getActivity());
list();
LinearLayoutManager MyLayoutManager = new LinearLayoutManager(getActivity());
MyLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setAdapter(new Adapter(list));
return view;
}
public class Adapter extends RecyclerView.Adapter<Adapter.MyviewHolder>{
// private ArrayList<Card> list;
public Adapter(ArrayList<Card> data) {
list = data;
}
public class MyviewHolder extends RecyclerView.ViewHolder{
public TextView textView;
public ImageView imageView;
public MyviewHolder(View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.textView);
imageView = (ImageView) itemView.findViewById(R.id.imageView);
}
}
#Override
public MyviewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_row,parent,false);
return new MyviewHolder(view);
}
#Override
public void onBindViewHolder(MyviewHolder holder, int position) {
Card card = list.get(position);
holder.textView.setText(card.getName());
Glide.with(getActivity()).load(card.getImg()).into(holder.imageView);
}
#Override
public int getItemCount() {
return list.size();
}
}
public void list() {
JsonObjectRequest object = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try{
JSONArray array = response.getJSONArray("photo");
for (int i = 0; i <array.length() ; i++) {
JSONObject temp = array.getJSONObject(i);
Card card = new Card();
card.setName(temp.getString("profile_id"));
card.setImg(temp.getString("image_url"));
list.add(card);
}
}catch (Exception ex){
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
mRequestQueue.add(object);
}
}
Volley is asynchronus, so when you call:
recyclerView.setAdapter(new Adapter(list));
just a few milliseconds after you enqueued your request, It's very likely that the list is still empty because Volley hasn't received any response yet. You should set your adapter once you get the response inside the onResponse callback.
Related
My recyclerview is not populating inside fragment. I am getting proper response from volley. I have parsed the JSON in arraylist in proper format only problem is that recyclerview is not populating.
MyFragment.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_undekha_tadka, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
myVolleyOperation(view);
return view;
}
private void myVolleyOperation(View v) {
volleySingleton = VolleySingleton.getInstance();
requestQueue = volleySingleton.getRequestQueue();
String url = "http://abcd.com/undekha.html";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
jsonParsing(response);
Toast.makeText(getContext(), response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), "ERROR\n" + error.toString(), Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(stringRequest);
recyclerViewAdapter = new RecyclerViewAdapter(undekhaList, v.getContext());
layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(recyclerViewAdapter);
}
RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewHolder> {
ArrayList<UndekhaModel> myArrayList = new ArrayList<>();
Context context;
VolleySingleton volleySingleton;
ImageLoader imageLoader;
public RecyclerViewAdapter(ArrayList<UndekhaModel> myArrayList, Context context) {
this.myArrayList = myArrayList;
this.context = context;
volleySingleton = VolleySingleton.getInstance();
imageLoader = volleySingleton.getImageLoader();
}
#Override
public RecyclerViewAdapter.RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_row, parent, false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view, context, myArrayList);
return recyclerViewHolder;
}
#Override
public void onBindViewHolder(final RecyclerViewAdapter.RecyclerViewHolder holder, int position) {
UndekhaModel undekhaModel = myArrayList.get(position);
holder.title.setText(undekhaModel.getTitle());
String loadUrl = "http://img.youtube.com/vi/" + undekhaModel.getId() + "/0.jpg";
if (loadUrl!=null){
imageLoader.get(loadUrl, new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
holder.thumbnail.setImageBitmap(response.getBitmap());
}
#Override
public void onErrorResponse(VolleyError error) {
holder.thumbnail.setImageResource(R.mipmap.ic_launcher);
}
});
}
}
#Override
public int getItemCount() {
return myArrayList.size();
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder {
TextView title;
ImageView thumbnail;
ArrayList<UndekhaModel> modelArrayList = new ArrayList<>();
Context context;
public RecyclerViewHolder(View itemView, final Context ctx, final ArrayList<UndekhaModel> modelArrayList) {
super(itemView);
this.context = ctx;
this.modelArrayList = modelArrayList;
title = (TextView) itemView.findViewById(R.id.tvTitle);
thumbnail = (ImageView) itemView.findViewById(R.id.ivShow);
}
}
}
Your method jsonParsing() needs to populate data for your RecyclerViewAdapter, needs to notify of the update and the adapter needs to return the correct count of items it is managing. Right now its getItemCount() is always returning 0, so the RecyclerView does not think there is anything to show.
Same issue than here
https://stackoverflow.com/a/35802948/2144418
Try setting the adapter before the layout manager
Change the last two lines on myVolleyOperation to this
recyclerView.setAdapter(recyclerViewAdapter);
recyclerView.setLayoutManager(layoutManager);
homepageThis is my fragment class
public class Premiums extends Fragment {
private RecyclerView recyclerPremium;
private RecyclerView.LayoutManager mLayoutManager;
private List<FeaturedAddDetails> featuredAddDetailsList = new ArrayList<>();
private List<PremiumDetails> premiumDetailslist = new ArrayList<>();
private NewestAdapter newestAdapter;
private PremiumAdapter premiumAdapter;
private String jsonResponse;
private PremiumDetails premiumDetails;
private JSONObject jsonobject;
public Premiums() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View mainView = inflater.inflate(R.layout.premium_fragment, container, false);
recyclerPremium = (RecyclerView) mainView.findViewById(R.id.recycler_premium);
premiumAdd();
premiumAdapter = new PremiumAdapter(getActivity().getApplicationContext(), premiumDetailslist);
recyclerPremium.setAdapter(premiumAdapter);
return mainView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
recyclerPremium.setLayoutManager(mLayoutManager);
recyclerPremium.setHasFixedSize(true);
}
private void premiumAdd() {
PremiumRequestHandler premiumHandler = new PremiumRequestHandler("premiumADD");
premiumHandler.executeAsStringRequest(new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("response", response);
JSONArray jsonarray = null;
try {
jsonarray = new JSONArray(response);
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < jsonarray.length(); i++) {
try {
jsonobject = jsonarray.getJSONObject(i);
Log.e("id", String.valueOf(jsonobject.getInt("id")));
premiumDetails = new PremiumDetails(jsonobject.getInt("id"),
jsonobject.getInt("userid"),
jsonobject.getInt("mobile"),
jsonobject.getInt("cityid"),
jsonobject.getInt("price"),
jsonobject.getInt("comments"),
jsonobject.getInt("created"),
jsonobject.getInt("categoryid"),
jsonobject.getInt("MainCategoryID"),
jsonobject.getInt("views"),
jsonobject.getInt("ImageCount"),
jsonobject.getInt("storeid"),
jsonobject.getString("title"),
jsonobject.getString("default_photo"),
jsonobject.getString("CityName"),
jsonobject.getString("CategoryName"),
jsonobject.getString("currency"),
jsonobject.getString("description"));
premiumDetailslist.add(premiumDetails);
premiumAdapter.setPremiumDetails(premiumDetailslist);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new BaseRequest.ErrorResponseCallback() {
#Override
public void onError(Exception exception) {
}
});
}
This is my adapter class
public class PremiumAdapter extends RecyclerView.Adapter<PremiumAdapter.MyViewHolderPremium> {
private List<PremiumDetails> premiumDetailsList;
private ImageLoader imageLoader;
private Context context;
public PremiumAdapter(Context context, List<PremiumDetails> premiumDetailsList) {
this.premiumDetailsList = premiumDetailsList;
this.context = context;
notifyDataSetChanged();
}
public void setPremiumDetails(List<PremiumDetails> premiumDetailsList) {
this.premiumDetailsList = premiumDetailsList;
notifyDataSetChanged();
}
public class MyViewHolderPremium extends RecyclerView.ViewHolder {
private TextView txtTitle,txtDescription,txtCityName,txtPrice,txtCategory,txtHour,txtPhotoNo;
private NetworkImageView imgPhoto;
public MyViewHolderPremium(View itemView) {
super(itemView);
txtTitle = (TextView)itemView.findViewById(R.id.txt_title_fad);
txtDescription = (TextView)itemView.findViewById(R.id.description_fad);
txtCityName = (TextView)itemView.findViewById(R.id.city_name_fad);
txtPrice = (TextView)itemView.findViewById(R.id.price_fad);
txtCategory = (TextView)itemView.findViewById(R.id.category_fad);
txtHour = (TextView)itemView.findViewById(R.id.hours_fad);
txtPhotoNo = (TextView)itemView.findViewById(R.id.txt_photo_no_fad);
imgPhoto=(NetworkImageView)itemView.findViewById(R.id.img_photo_lod_fad);
}
}
#Override
public MyViewHolderPremium onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.featured_ad_adapter_layout,parent,false);
final MyViewHolderPremium myViewHolderPremium = new MyViewHolderPremium(itemView);
return myViewHolderPremium;
}
#Override
public void onBindViewHolder(MyViewHolderPremium holder, int position) {
PremiumDetails premiumDetails = premiumDetailsList.get(position);
holder.txtTitle.setText(premiumDetails.getTitle());
holder.txtDescription.setText(premiumDetails.getDescription());
holder.txtCityName.setText(premiumDetails.getCityName());
holder.txtPrice.setText(Integer.toString(premiumDetails.getPrice()));
holder.txtCategory.setText(premiumDetails.getCategoryName());
holder.txtHour.setText(Integer.toString(premiumDetails.getCreated()));
holder.txtPhotoNo.setText(Integer.toString(premiumDetails.getImageCount())+" photos " );
try {
imageLoader= VolleyHandler.getImageLoader();
} catch (Exception e) {
e.printStackTrace();
}
//imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
//imageLoader.get(featuredAddDetails.getDefault_photo(), ImageLoader.getImageListener(holder.imgPhoto, R.mipmap.ic_launcher, android.R.drawable.ic_dialog_alert));
holder.imgPhoto.setImageUrl(premiumDetails.getDefault_photo(),imageLoader);
}
#Override
public int getItemCount() {
Log.e("size", String.valueOf(premiumDetailsList.size()));
return premiumDetailsList.size();
}}
I am getting error on showing values but I got values from json and I can't add it to adapter and model class, plz help me I look stackoverflow whole day but I can't find my issue
my getItemCount() is showing as 0"
You are setting the adapter and then you are calling premiumAdd() method.First call that method and then set the adapter.
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View mainView = inflater.inflate(R.layout.premium_fragment, container, false);
recyclerPremium = (RecyclerView) mainView.findViewById(R.id.recycler_premium);
premiumAdd();
premiumAdapter = new PremiumAdapter(getActivity().getApplicationContext(), premiumDetailslist);
recyclerPremium.setAdapter(premiumAdapter);
return mainView;
Try notifyDataSetChanged() after setting data in the Constructor of your Adapter
[EDIT] Whenever your data changes, you need to inform your Adapter about it also, then call notifyDataSetChanged() on it.
You are probably setting empty data into the Adapter, your List changes, but the Adapter does not know about it.
[Update]
In addition to your Adapter constructor, add a setData(List) to your adapter to change your dataset at runtime.
public void setPremiumDetails(List<PremiumDetails> premiumDetailsList) {
this.premiumDetailsList = premiumDetailsList;
notifyDataSetChanged();
}
When your request in premiumAdd() returns, and you receive a new set of data, you call setPremiumDetails on your Adapter with the new data and the List will update.
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View mainView = inflater.inflate(R.layout.premium_fragment, container, false);
recyclerPremium = (RecyclerView) mainView.findViewById(R.id.recycler_premium);
mLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
recyclerPremium.setLayoutManager(mLayoutManager);
recyclerPremium.setHasFixedSize(true);
premiumAdd();
premiumAdapter = new PremiumAdapter(getActivity().getApplicationContext(), premiumDetailslist);
recyclerPremium.setAdapter(premiumAdapter);
return mainView;
}
and remove premiumAdapter.notifyDataSetChanged();
added adapter code:
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.ViewHolder> {
ArrayList<Model> dataset;
public RVAdapter(ArrayList<Model> dataset) {
this.dataset = dataset;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_item,parent,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Model model = dataset.get(position);
holder.name.setText(model.name) ;
holder.status.setText(model.status);
if (model.status.equalsIgnoreCase("good"))
holder.ivStatus.setImageResource(R.drawable.ic_tick_48);
else
holder.ivStatus.setImageResource(R.drawable.ic_delete_48);
}
#Override
public int getItemCount() {
Log.e("TAG","SIZE: "+dataset.size());
return dataset.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView name;
TextView status;
ImageView ivStatus;
RelativeLayout parent;
public ViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.rv_item_name);
status = (TextView) itemView.findViewById(R.id.rv_item_status);
ivStatus = (ImageView) itemView.findViewById(R.id.rv_item_iv);
parent = (RelativeLayout) itemView.findViewById(R.id.rv_item_parent);
}
}
}
your notifiy adapter on every single add
for (...){
....
premiumDetailslist.add(premiumDetails);
premiumAdapter.notifyDataSetChanged();// called every time wrong
}
also provide what exact error log says
and move the notifyDataSetChanged() after the for not in the loop
if no data is showing try recyclerview.invalidate , but i wont particularly do that way, would try debugging, log every step, inspect with method in the expected sequence isnt working
I am using RecyclerView to display my products, problem is when if I select the first products and scroll down to the end of list I see different products selected and when i scroll back to top of list the first item is not selected.
My Adapter
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {
String u = "http://192.185.52.231/~sabby070/hyype/";
Context context1;
private java.util.List<ProductDetails> List;
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_list, parent, false);
return new MyViewHolder(itemView);
}
public RecyclerAdapter(List<ProductDetails> DataList, FragmentActivity activity) {
this.List = DataList;
context1 = activity;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView Likecount;
public ImageView Image;
public ImageView Imagelike, ImageUnlike;
public MyViewHolder(View view) {
super(view);
Likecount = (TextView) view.findViewById(R.id.textView_itemPrice);
Image = (ImageView) view.findViewById(R.id.imageView_imgtosold);
Imagelike = (ImageView)view.findViewById(R.id.Like_Button);
ImageUnlike = (ImageView)view.findViewById(R.id.UnLike_Button);
}
}
#Override
public void onBindViewHolder(final RecyclerAdapter.MyViewHolder holder, final int position) {
final ProductDetails detail = List.get(position);
holder.Likecount.setText(detail.getLikeCount());
Glide.with(context1).load(u+detail.getImage()).override(600, 200).diskCacheStrategy(DiskCacheStrategy.ALL).into(holder.Image);
holder.Image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context1, ""+position, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context1, Buy_Product.class);
intent.putExtra("Product Name",detail.getLikeCount());
intent.putExtra("Product Image",detail.getImage());
context1.startActivity(intent);
}
});
holder.Imagelike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.Imagelike.getVisibility()==View.VISIBLE)
{
holder.Imagelike.setVisibility(View.GONE);
holder.ImageUnlike.setVisibility(View.VISIBLE);
}
}
});
holder.ImageUnlike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.ImageUnlike.getVisibility()==View.VISIBLE)
{
holder.Imagelike.setVisibility(View.VISIBLE);
holder.ImageUnlike.setVisibility(View.GONE);
}
}
});
}
#Override
public int getItemCount() {
return List.size();
}
}
My class
public class Men_Fragment extends Fragment {
static String URL = "http://192.185.52.231/~sabby070/hyype/index.php?action=timeline&user_id=53&post_category=timeline";
private List<ProductDetails> DataList = new ArrayList<>();
private RecyclerView recyclerView;
private RecyclerAdapter rAdapter;
String img;
String a;
Boolean list[];
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_men_, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.men_recycler_view);
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(response);
for (int i = 0; i < response.length(); i++) {
JSONObject obj = jsonObject.getJSONObject(String.valueOf(i));
a = obj.getString("like_count");
img = obj.getString("video_thumb");
final ProductDetails details = new ProductDetails(a, img);
DataList.add(details);
rAdapter = new RecyclerAdapter(DataList, getActivity());
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(rAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "" + error, Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
return view;
}
}
You have to take List(with boolean) and store selected values in that list and then use those values in onBindView()
In your ProductDetails class add a field boolean selected;
In your onClick() add List.get(position).setSelected(!List.get(position).isSelected()); to check/uncheck as needed.
Finaly in your onBindViewHolder(...) add
if(List.get(position).isSelected()){
holder.Imagelike.setVisibility(View.VISIBLE);
}else{
holder.ImageUnlike.setVisibility(View.GONE);
}
please any one explain RecyclerView in fragment using volley to get json data.
Already i refered below link coding Google recyclerview in fragment
this is my first project in android, so i cannot understand that coding.
Please any one help me.
My fragmnet Coding:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View drawer = inflater.inflate(R.layout.fragment_progress, container, false);
orderLists = new ArrayList<>();
getProgressData();
recyclerView = (RecyclerView) drawer.findViewById(R.id.progress);
adapter = new ProgressOrderListAdapter(orderLists, this);
adapter.clearAdaptor();
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return recyclerView;
}
private void getProgressData(){
String mobilecustomertoken = SharedPreferencesManager.readPreferenceString("MobileCustomerToken", "D/N");
JSONObject progressData = new JSONObject();
try{
progressData.put("mobilecustomertoken", mobilecustomertoken);
JsonObjectRequest progressObject = new JsonObjectRequest(1, Common.OrderDetails + "progress", progressData, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject progressResponse) {
Log.d("Responseprogress", progressResponse.toString());
try {
int status = progressResponse.getInt("status");
if(status == 1) {
progressOrderProgress(progressResponse);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Log.d("Response", "PROGRESS ERROR");
}
});
progressObject.setShouldCache(false);
ServiceBellApp.getInstance().addToRequestQueue(progressObject);
}
catch (JSONException localJSONException){
localJSONException.printStackTrace();
return;
}
}
private void progressOrderProgress(JSONObject progressResponse) throws JSONException {
JSONArray result = progressResponse.getJSONArray("orderdata");
OrderList orderListModule = new OrderList();
for(int i=0; i<result.length(); i++){
JSONObject orderData = result.getJSONObject(i);
orderListModule.setPackage_name(orderData.getString("package_name"));
orderListModule.setOrderdate(orderData.getString("orderdate"));
orderListModule.setServicedate(orderData.getString("servicedate"));
orderListModule.setServicetime(orderData.getString("servicetime"));
orderListModule.setOrderid(orderData.getString("orderid"));
orderListModule.setOrdstatus(orderData.getString("ordstatus"));
orderListModule.setOrderamount(orderData.getInt("orderamount"));
}
orderLists.add(orderListModule);
}
My adapter code:
public class OrderListAdapter extends RecyclerView.Adapter<OrderListAdapter.ViewHolder> {
List<OrderList> List;
private FragmentPending mContext;
public OrderListAdapter(List<OrderList> List, FragmentPending context) {
this.mContext = context;
this.List = List;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.order_list_view, null);
ViewHolder holder = new ViewHolder(view);
// this is where the each item is inflated.
return holder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
OrderList orderListsPos = List.get(position);
// this is where the data for each item is assigned
holder.textViewPackageName.setText(orderListsPos.getPackage_name());
holder.textOrderdate.setText(orderListsPos.getOrderdate());
holder.textServicedate.setText(orderListsPos.getServicedate());
holder.textServicetime.setText(orderListsPos.getServicetime());
holder.textOrderid.setText(orderListsPos.getOrderid());
holder.textOrderamount.setText("Rs." + orderListsPos.getOrderamount());
holder.textStatus.setText(orderListsPos.getOrdstatus());
}
#Override
public int getItemCount() {
return List.size();
}
public void clearAdaptor() {
List.clear();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView textViewPackageName;
public TextView textServicedate;
public TextView textServicetime;
public TextView textOrderdate;
public TextView textOrderid;
public TextView textOrderamount;
public TextView textStatus;
public ViewHolder(View itemView) {
super(itemView);
textViewPackageName = (TextView) itemView.findViewById(R.id.productName);
textOrderdate = (TextView) itemView.findViewById(R.id.orderdate);
textOrderid = (TextView) itemView.findViewById(R.id.orderno);
textOrderamount = (TextView) itemView.findViewById(R.id.orderprice);
textStatus = (TextView) itemView.findViewById(R.id.orderstatus);
}
}}
First you need four things
1 ) layout that holds the each recycler view layout item
2 ) A view holder for creating each layout
3 ) A Model Class to holds the data
4 ) Recycler Adaptor which deals with the data for the Each Layout item
FIrst create a layout item
for eample lets create a single view with only TextView in it
XML
each_item.xml
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:gravity="start|center_vertical"
android:textColor="#color/white"
android:textSize="18sp" />
and lets now create a view holder
i will post both code for the view holder and RecyclerAdaptor
public class Adaptor extends RecyclerView.Adapter<Adaptor.ViewHolder> {
List<Model> List = Collections.emptyList();
private Context mContext;
private LayoutInflater inflater;
public Adaptor(Context context, List<Model> List) {
inflater = LayoutInflater.from(context);
this.mContext = context;
this.List = List;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.each_item, parent, false);
final ViewHolder holder = new ViewHolder(view);
// this is where the each item is inflated.
return holder;
}
#Override
public void onBindViewHolder(WinnersViewHolder holder, int position) {
Model mModel = List.get(position);
// this is where the data for each item is assigned
holder.nameView.setText("" + mModel.getName());
}
#Override
public int getItemCount() {
return List.size();
}
public void clearAdaptor() {
List.clear();
}
public class ViewHolder extends RecyclerView.ViewHolder {
protected TextView nameView;
public ViewHolder(View itemView) {
super(itemView);
this.nameView = (TextView) itemView.findViewById(R.id.name);
}
}
}
Now the model class
public class Model {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name= name;
}
}
Now the back end is done, Lets implement it on the Fragment
List<Model> List = new ArrayList<>();
private RecyclerView mRecyclerView;
private Adaptor adaptor;
public Fragment() {
// constructor of fragment
// Required empty public constructor
}
in the onCreatView() get the id of recyclerView
View fragmentView = inflater.inflate(R.layout.fragment_layout, container, false);
mRecyclerView = (RecyclerView) fragmentView .findViewById(R.id.recycler_view);
and then pass the data to the Adaptor by creating its object
adaptor = new Adaptor(getContext(), List);
adaptor.clearAdaptor();
mRecyclerView.setAdapter(adaptor);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
You are done now, only thing pending is if you are accessing data form server call notifyDataSetChanged() or adaptor = new Adaptor(getContext(), getList()); where the getList() returns the Model data and do not call adaptor.clearAdaptor() .
hope this helps ..
EDIT
you can two ways infalte the each layout item .. one is above and second is in onCreateViewHolder
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.each_item, null);
Check this link It is really helpful for beginners for understanding concepts from start to mastering the RecyclerView.
https://github.com/codepath/android_guides/wiki/Using-the-RecyclerView
Hope this helps you to understand recycler view concepts.
RecycerView + Fragment + Volley
Fragment Code:
public class DogListFragment extends Fragment{
private RecyclerView rv;
private StaggeredGridLayoutManager llm;
private DogListAdapter adapter;
private ArrayList<DogModel> dogList;
private Context context;
public static DogListFragment getInstance(){
return new DogListFragment();
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
dogList = new ArrayList<>();
adapter = new DogListAdapter(context, dogList, this);
getListFromServer();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.fragment_dog_list, parent, false);
rv = view.findViewById(R.id.rv);
llm = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
rv.setLayoutManager(llm);
rv.setAdapter(adapter);
return view;
}
public void getListFromServer(){
String url = "https://dog.ceo/api/breed/hound/images/random/20";
RequestQueue requestQueue = Volley.newRequestQueue(context);
StringRequest request = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("message");
for(int i=0;i<array.length();i++){
String imageUrl = array.getString(i);
dogList.add(new DogModel(imageUrl));
}
adapter.updateDataSet(dogList);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
requestQueue.add(request);
}
}
Full code
Woof Repository
It has the following implementations
Fragment communication via interface
Reusing fragment by
getSupportFragmentManager().findFragmentByTag(TAG)
Which lifecycle method should have API call so that it is called just
once
How to save RecylcerView state in Fragment (Scroll position + content)
Pagination in RecyclerView
Rest Calls (Volley)
Image Rendering (Glide)
JSON Parsing
This is my Fragment class in here I can't create instance of Person class. While try am to create instance of Person class, showing error as Person(String,String) in Person can not be applied to zero.
public class MainActivityFragment extends Fragment {
private final List<Person> mPersonList = new ArrayList<>();
public MainActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
Context context = getActivity();
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(context);
recyclerView.setLayoutManager(layoutManager);
final RVAdapter rvAdapter = new RVAdapter(mPersonList);
recyclerView.setAdapter(rvAdapter);
RequestQueue requestQueue = Volley.newRequestQueue(context);
String url = "http://192.16.1.100/api/persons";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
Person person=new Person();
person.phone_name = jsonObject.getString("name");
person.phone_price = jsonObject.getString("dddd");
mPersonList.add(i, person);
}
rvAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
});
requestQueue.add(jsonArrayRequest);
return view;
} }
My Person class
class Person {
public String phone_name;
public String phone_price;
Person(String phone_name, String phone_price) {
this.phone_name = phone_name;
this.phone_price = phone_price;
} }
My Adapter class is
public class RVAdapter extends
RecyclerView.Adapter<RVAdapter.PersonViewHolder> {
List<Person> persons;
RVAdapter(List<Person> persons) {
this.persons = persons;
}
#Override
public PersonViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview,
parent, false);
PersonViewHolder pvh = new PersonViewHolder(v);
return pvh;
}
#Override
public void onBindViewHolder(PersonViewHolder holder, int position) {
holder.phoneName.setText(persons.get(position).phone_name);
holder.phonePrice.setText(persons.get(position).phone_price);
}
#Override
public int getItemCount() {
if (persons != null) {
return persons.size();
}
return 0;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public static class PersonViewHolder extends RecyclerView.ViewHolder {
CardView cv;
TextView phoneName;
TextView phonePrice;
PersonViewHolder(View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.card_view);
phoneName = (TextView) itemView.findViewById(R.id.phone_name);
phonePrice = (TextView) itemView.findViewById(R.id.phone_price);
}
} }
please try to change the following things
String phone_name = jsonObject.getString("name"
String phone_price = jsonObject.getString("dddd");
Person person=new Person(phone_name,phone_price);