I'm creating an app similar to the instagram app but only admin can add contents. i used python django for my backend but when i add new item to my django database, it comes last on the recyclerview. I want it to be in a way that, when i add new item, it comes first when you open my app like the way instagram shows recent items first.
This is my custom Adapter class
public class DealAdapter extends RecyclerView.Adapter<DealAdapter.DealHolder> {
Context context;
ArrayList<Deal> arrayList;
public DealAdapter(Context context, ArrayList<Deal> arrayList) {
this.context = context;
this.arrayList = arrayList;
}
#Override
public DealHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.deal_cardview, parent, false);
DealHolder dealHolder = new DealHolder(v);
return dealHolder;
}
#Override
public void onBindViewHolder(DealHolder holder, int position) {
Deal deal = arrayList.get(position);
holder.title.setText(deal.getTitle());
Picasso.with(context).
load(deal.getImage()).
placeholder(R.drawable.loading).
error(android.R.drawable.stat_notify_error).
into(holder.image);
}
#Override
public int getItemCount() {
if(arrayList != null) {
return arrayList.size();
}else {
return 0;
}
}
public class DealHolder extends RecyclerView.ViewHolder {
TextView title;
ImageView image;
public DealHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.tvTitle);
image = (ImageView) itemView.findViewById(R.id.ivImage);
}
}
}
This is my main Activity class
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
String TAG = "MainActivity";
ImageButton ibMore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.rvRecyclerview);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
String url = "http://192.168.43.2/api/deals/?format=json";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
ArrayList<Deal> userList = new JsonConverter<Deal>().
toArrayList(response, Deal.class);
DealAdapter adapter = new DealAdapter(getApplicationContext(), userList);
recyclerView.setAdapter(adapter);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.toString());
Toast.makeText(getApplicationContext(), "Something Went wrong: " + "'" + error + "'", Toast.LENGTH_LONG).show();
}
});
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
}
}
Okay so this is what worked for me. After getting JSON and converting to ArrayList, i called it in "Collections.reverse(arrayList);" before adding it to the adapter as shown below.
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
ArrayList<Deal> userList = new JsonConverter<Deal>().
toArrayList(response, Deal.class);
Collections.reverse(userList);
DealAdapter adapter = new DealAdapter(getApplicationContext(), userList);
recyclerView.setAdapter(adapter);
}
Believe me, only this single line worked for me. Use this :
Collections.reverse(list);
Where list will be your list containing any type of object
Max Billionaire,
If your "userList" contain single item then do like this
adapter.add(0, userList.get(0));
adapter.notifyItemInserted(0);
if you have adapter instance then just refresh the adapter like this
adapter.notifyDataSetChanged();
instead
DealAdapter adapter = new DealAdapter(getApplicationContext(), userList);
recyclerView.setAdapter(adapter);
To display the recent added data to the top of the list do this
yourArrayListOfData.add(0, newAddedData);
adapter.notifyDataSetChanged();
Related
When I am writing the title of my question, then this site recommends me some answer but I can't find my answer that's why I am writing a new one. I am trying simple RecyclerView and it's run successfully but when I am fetching data from internet using volley library then I face this error
here is my code
BusinessActivity.java
public class BusinessActivity extends AppCompatActivity {
private final String URL = "https://api.myjson.com/bins/a44ec";
private JsonArrayRequest request;
private RequestQueue requestQueue;
private List<ArticleModel> articleList;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business);
articleList = new ArrayList<>();
recyclerView = findViewById(R.id.business_recyclerView);
jsonParse();
}
private void jsonParse() {
request = new JsonArrayRequest(URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject = null;
for (int i=0;i<response.length();i++){
try {
jsonObject = response.getJSONObject(i);
ArticleModel article = new ArticleModel();
article.setTitle(jsonObject.getString("title"));
article.setAuthor(jsonObject.getString("author"));
article.setDescription(jsonObject.getString("description"));
article.setPublishedAt(jsonObject.getString("publishedAt"));
article.setUrlToImage(jsonObject.getString("urlToImage"));
articleList.add(article);
} catch (JSONException e) {
e.printStackTrace();
}
}
setRecyclerView(articleList);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(BusinessActivity.this);
requestQueue.add(request);
}
private void setRecyclerView(List<ArticleModel> articleList) {
BusinessAdapter adapter = new BusinessAdapter(articleList,this);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
}
BusinessAdapter.java
public class BusinessAdapter extends RecyclerView.Adapter<BusinessAdapter.MyViewHolder> {
private List<ArticleModel> articleModels;
private Context context;
RequestOptions options;
public BusinessAdapter(List<ArticleModel> articleModels, Context context) {
this.articleModels = articleModels;
this.context = context;
options = new RequestOptions().centerCrop().placeholder(R.drawable.ic_launcher_background).error(R.drawable.ic_launcher_background);
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.category_row,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
ArticleModel articleModel = articleModels.get(position);
holder.title.setText(articleModel.getTitle());
holder.author.setText(articleModel.getAuthor());
holder.desc.setText(articleModel.getDescription());
holder.date.setText(articleModel.getPublishedAt());
Glide.with(context).load(articleModel.getUrlToImage()).apply(options).into(holder.image);
}
#Override
public int getItemCount() {
return articleModels.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView title,author,desc,date;
ImageView image;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.title);
author = itemView.findViewById(R.id.author);
desc = itemView.findViewById(R.id.detail);
date = itemView.findViewById(R.id.date);
image = itemView.findViewById(R.id.image);
}
}
}
Error log
2020-04-01 00:15:53.117 8821-8821/com.atc.newsappproject E/RecyclerView: No adapter attached; skipping layout
2020-04-01 00:15:53.118 1752-1787/? E/storaged: getDiskStats failed with result NOT_SUPPORTED and size 0
How can I solve this?
Thank you.
This error usually happens when you don't set the RecyclerView when you create your Fragment or Activity. To fix this you need to:
Set your RecyclerView in onCreate instead of when you pick up result. You set it with an empty list.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business);
articleList = new ArrayList<>();
recyclerView = findViewById(R.id.business_recyclerView);
setRecyclerView(articleList);
jsonParse();
}
You create a setter in your Adapter
public void setArticles(ArrayList<ArticleModel> articles){
this.articles = articles;
notifyDataSetChanged();
}
Create private BusinessAdapter adapter; below private RecyclerView recyclerView;
Finally in your onResponse you call adapter.setArticles(articlesList);
Here is a link with a lot of solutions if you still got issue: recyclerview No adapter attached; skipping layout
I'm trying to show the details of students in a recyclerview, obtained from a web service. The app works in a way that in an Activity, it opens list of students and then on touch of a student, it opens another activity which will show the details of that particular student in a recyclerview.
Problem:
I sometimes get an empty recyclerview item either above or below the valid item with data. I tried calling StuDetailsDataAdapterClassList.clear(); but it doesn't fix the issue. Some times it works fine but I don't understand why it is happening. Your help is valuable for me.
public class StudentDetailsActivity extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView recyclerView2;
RecyclerView.Adapter recyclerViewAdapter;
RecyclerView.Adapter recyclerViewAdapter2;
LinearLayoutManager recyclerViewlayoutManager;
RequestQueue requestQueue ;
RequestQueue requestQueue2 ;
List<StudentDataModel> StuDetailsDataAdapterClassList;
String stuIDForParse;
StudentDataModel GetStuDataModel = new StudentDataModel();
.....
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_personnel_details);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
collapsingToolbarLayout = (SubtitleCollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView4);
recyclerView2 =(RecyclerView)findViewById(R.id.recyclerView5);
recyclerViewlayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerViewlayoutManager);
StuDetailsDataAdapterClassList=new ArrayList<>();
LinearLayoutManager layoutManager
= new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
recyclerView2.setLayoutManager(layoutManager);
//I have a horizontal recyclerview below the vertical recyclerview. This is the layout manager for that recyclerview.
recyclerView2.setNestedScrollingEnabled(false);
//Set collapse & expanded title color
collapsingToolbarLayout.setExpandedSubtitleTextColor(getResources().getColor(R.color.divider));
setSupportActionBar(toolbar);
//Enable back button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
....
//clearing list
StuDetailsDataAdapterClassList.clear();
PIC__WEB_CALL();
STU_WEB_CALL();
}
public void STU_WEB_CALL(){
String HTTP_SERVER_URL= String.format("http://www.student.com/%1$s",stuIDForParse);
JsonArrayRequest jsArrRequest = new JsonArrayRequest
(Request.Method.GET, HTTP_SERVER_URL, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
RES_PER_PARSE_DATA_AFTER_WEBCALL(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
}){
};
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsArrRequest);
}
public void RES_PER_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetStuDataModel.setDob(json.getString("Date_Of_Birth"));
GetStuDataModel.setStuName(json.getString("Name"));
GetStuDataModel.setGradeName(json.getString("Grade"));
//Set the title on collapsing toolbar
collapsingToolbarLayout.setTitle(GetStuDataModel.getFullName());
} catch (JSONException e) {
e.printStackTrace();
}
}
if (array.length() != 0) {
StuDetailsDataAdapterClassList.add(GetStuDataModel);
collapsingToolbarLayout.setSubtitle(GetStuDataModel.getPerTitle());
recyclerViewAdapter = new StudentDetailsAdapter(StuDetailsDataAdapterClassList, this);
recyclerView.setAdapter(recyclerViewAdapter);
}
}
public void Horizontal_RecyclerView_WEB_CALL(){
//....more code
}
adapter
public class StudentDetailsAdapter extends RecyclerView.Adapter<StudentDetailsAdapter.ViewHolder> {
Context context;
public List<StudentDataModel> dataModels;
public StudentDetailsAdapter(List<StudentDataModel> getDataAdapter, Context context){
super();
Log.i("LPLP","I'm here");
this.dataModels = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.student_details_card, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final StudentDetailsAdapter.ViewHolder viewHolder, final int position) {
final StudentDataModel dataAdapter = dataModels.get(position);
viewHolder.grade.setText(dataAdapter.getGradeName());
viewHolder.stuName.setText(dataAdapter.getStuName());
viewHolder.dob.setText(dataAdapter.getDob());
}
#Override
public int getItemCount() {
return dataModels.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView grade;
public TextView stuName;
public TextView dob;
ConstraintLayout constraintLayout;
public ViewHolder(View itemView) {
super(itemView);
grade=(TextView)itemView.findViewById(R.id.textViewGrade);
stuName=(TextView)itemView.findViewById(R.id.textViewStuName);
dob=(TextView)itemView.findViewById(R.id.textViewDOB)
constraintLayout=(ConstraintLayout)itemView.findViewById(R.id.constrainLayout);
}
}
}
I have a RecycleView to which I give an Array of Post objects. When it's loaded first time, everything works fine but trying to replace the data or just entering in the Fragment again then the RecycleView does not show anything. Also I have checked the size of the new data and it's different from zero. Here is my code:
// Init the list
list = (RecyclerView) view.findViewById(R.id.list);
list.setLayoutManager(new LinearLayoutManager(mContext));
...
if (adapter != null) {
adapter.replaceCurrentPosts(new ArrayList<>(postList));
}
else {
adapter = new PostAdapter(mContext, new ArrayList<>(postList), this);
list.setAdapter(adapter);
}
...
public PostAdapter(Context context, List<Post> posts, onPostElementClickListener listener) {
this.context = context;
this.posts = posts;
this.mListener = listener;
}
public void replaceCurrentPosts(List<Post> newPosts) {
this.posts.clear();
this.posts.addAll(newPosts);
this.notifyDataSetChanged();
}
#Override
public int getItemCount() {
return posts.size();
}
package com.example.jiteshmohite.myapplication;
public class PostAdapter extends RecyclerView.Adapter {
private Context context;
private List<Post> posts;
private onPostElementClickListener mListener;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView mTextView;
public ViewHolder(View v) {
super(v);
mTextView = (TextView) v.findViewById(R.id.info_text);
}
}
public PostAdapter(Context context, List<Post> posts, onPostElementClickListener listener) {
this.context = context;
this.posts = posts;
this.mListener = listener;
}
public void replaceCurrentPosts(List<Post> newPosts) {
posts.clear();
posts = newPosts;
this.notifyDataSetChanged();
}
#Override
public PostAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_text_view, parent, false);
// set the view's size, margins, paddings and layout parameters
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(PostAdapter.ViewHolder holder, final int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.mTextView.setText(posts.get(position).getName());
holder.mTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListener.onClick(position);
}
});
}
#Override
public int getItemCount() {
return posts.size();
}
interface onPostElementClickListener {
public void onClick(int pos);
}
}
private RecyclerView list;
private PostAdapter postAdapter;
private RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycler_example);
list = (RecyclerView) findViewById(R.id.list);
layoutManager = new LinearLayoutManager(getApplicationContext());
list.setLayoutManager(layoutManager);
postAdapter = new PostAdapter(getApplicationContext(), getPostData(), listener);
list.setAdapter(postAdapter);
}
private PostAdapter.onPostElementClickListener listener = new PostAdapter.onPostElementClickListener() {
#Override
public void onClick(int pos) {
Toast.makeText(getApplicationContext(), pos + "" , Toast.LENGTH_SHORT).show();
List<Post> posts = getPostData();
posts.get(pos).setName("abc");
postAdapter.replaceCurrentPosts(posts);
}
};
// get post list which contains name
public List<Post> getPostData() {
Post post = new Post();
post.setName("xyz");
List<Post> posts = new ArrayList<Post>();
posts.add(post);
posts.add(post);
posts.add(post);
posts.add(post);
posts.add(post);
return posts;
}
}
I suggesting rather then notifyDataSetChanged() you should refer notifyItemChange which modify specific positions.
please let me know if it is not work for you.
why don't you try to add one element (or maybe more) instead of remove all and re-add all items?
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);
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