I am trying to add recyclerview to another recyclerview.
Like Sub Category Recyclerview in its Category RecyclerViews.
problem is that I am getting All categorie's sub category item list in last item of category list.
means
Cat1
cat2
catn(then below this list of subcat1, subcat2....so on)
but it should be like cat1 then in below subcat1 and so on...
here is MainActivity code from where I am calling the api and passing adapter to recyclerview
private void getCategory() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, CategoryUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
JSONArray jsonArray = obj.getJSONArray("DATA");
Log.v("Cat Response", response.toString());
for (int i = 0; i < jsonArray.length(); i++) {
DataModel Model = new DataModel();
JSONObject jsonObject = jsonArray.getJSONObject(i);
catId = jsonObject.getString("ID");
catTitle = jsonObject.getString("TITLE");
Model.setTITLE(catTitle);
Model.setID(catId);
catList.add(Model);
categoryAdaptor.getSubCategory(catId);
}
categoryAdaptor.notifyDataSetChanged();
} catch (JSONException e) {
System.out.print("Exception is :" + e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void setCatAdaptor() {
#SuppressLint("WrongConstant") LinearLayoutManager gridLayoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayout.VERTICAL, false);
recyclerView1.setLayoutManager(gridLayoutManager); // set LayoutManager to RecyclerView
// call the constructor of CustomAdapter to send the reference and data to Adapter
categoryAdaptor = new CategoryAdaptor(this, catList);
recyclerView1.setAdapter(categoryAdaptor);
}
here is category adapter
public class CategoryAdaptor extends RecyclerView.Adapter<CategoryAdaptor.MyViewHlder> {
private Activity activity;
private ArrayList<DataModel> list;
private SubCategoryAdaptor subcategoryAdaptor;
private ArrayList<SubCatModel> subCatList = new ArrayList<>();
private String SubCategoryUrl = "http://philiabeauty.com/reader-choice/controller-api.php?action=get_subcategory_by_category&id=";
private String Token = "&access_token=Ym9va19kZXRhaWxz";
private String imgRoot = "http://philiabeauty.com/reader-choice/";
private String subCatId, subCatTitle, subCatImage;
public CategoryAdaptor(Activity activity, ArrayList<DataModel> list) {
this.activity = activity;
this.list = list;
}
#NonNull
#Override
public MyViewHlder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.category_list_layout, viewGroup, false);
MyViewHlder my = new MyViewHlder(view);
return my;
}
#Override
public void onBindViewHolder(#NonNull MyViewHlder myViewHlder, int i) {
final DataModel model = list.get(i);
myViewHlder.catText.setText(model.getTITLE());
myViewHlder.catId.setText(model.getID());
setSubCatAdaptor(myViewHlder);
}
#Override
public int getItemCount() {
return list.size();
}
public void getSubCategory(String ID) {
String SubCategoryUrlFinal = SubCategoryUrl + ID + Token;
StringRequest stringRequest = new StringRequest(Request.Method.GET, SubCategoryUrlFinal, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
JSONArray jsonArray = obj.getJSONArray("DATA");
Log.v("SubCat Response", response.toString());
for (int i = 0; i < 3; i++) {
SubCatModel Model = new SubCatModel();
JSONObject jsonObject = jsonArray.getJSONObject(i);
subCatId = jsonObject.getString("ID");
subCatTitle = jsonObject.getString("TITLE");
subCatImage = imgRoot + jsonObject.getString("IMG_SRC");
Model.setSubCatIMG(subCatImage);
Model.setSubCatTITLE(subCatTitle);
Model.setSubCatID(subCatId);
subCatList.add(Model);
}
subcategoryAdaptor.notifyDataSetChanged();
} catch (JSONException e) {
System.out.print("Exception is :" + e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(activity);
requestQueue.add(stringRequest);
}
private void setSubCatAdaptor(MyViewHlder myView) {
Log.v("test", "test" );
#SuppressLint("WrongConstant") LinearLayoutManager gridLayoutManager = new LinearLayoutManager(activity, LinearLayout.HORIZONTAL, false);
myView.recyclerviewSubCat.setLayoutManager(gridLayoutManager); // set LayoutManager to RecyclerView
// call the constructor of CustomAdapter to send the reference and data to Adapter
subcategoryAdaptor = new SubCategoryAdaptor(activity, subCatList);
myView.recyclerviewSubCat.setAdapter(subcategoryAdaptor);
}
class MyViewHlder extends RecyclerView.ViewHolder {
private TextView catText, viewAllBtn, catId, tag;
private RecyclerView recyclerviewSubCat;
public MyViewHlder(#NonNull View itemView) {
super(itemView);
catText = itemView.findViewById(R.id.cat_name);
viewAllBtn = itemView.findViewById(R.id.viewAllBtn);
catId = itemView.findViewById(R.id.cat_id);
recyclerviewSubCat = itemView.findViewById(R.id.recyclerviewSubCat);
}
}
}
and here is the sub category adapter
public class SubCategoryAdaptor extends RecyclerView.Adapter<SubCategoryAdaptor.MyViewHlder> {
private Activity activity;
private ArrayList<SubCatModel> list;
public SubCategoryAdaptor(Activity activity, ArrayList<SubCatModel> list) {
this.activity = activity;
this.list = list;
}
#NonNull
#Override
public MyViewHlder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.subcat_list, viewGroup, false);
MyViewHlder my = new MyViewHlder(view);
return my;
}
#Override
public void onBindViewHolder(#NonNull MyViewHlder myViewHlder, int i) {
final SubCatModel model = list.get(i);
Log.v("data", model.getSubCatTITLE());
myViewHlder.subCatTitle.setText(model.getSubCatTITLE());
myViewHlder.subCatId.setText(model.getSubCatID());
String img = model.getSubCatIMG();
Picasso.get()
.load(img)
.placeholder(R.drawable.ic_book_black_24dp)
.fit()
.into(myViewHlder.subCatImage);
}
#Override
public int getItemCount() {
return list.size();
}
class MyViewHlder extends RecyclerView.ViewHolder {
private TextView subCatTitle, subCatId, subCatTag;
private ImageView subCatImage;
public MyViewHlder(#NonNull View itemView) {
super(itemView);
subCatTitle = itemView.findViewById(R.id.subcat_name);
subCatId = itemView.findViewById(R.id.subcat_id);
subCatTag = itemView.findViewById(R.id.subcat_tag);
subCatImage = itemView.findViewById(R.id.subcat_image);
}
}
}
Changed the sub category adapter declaration to viewHolder,
public class CategoryAdaptor extends RecyclerView.Adapter<CategoryAdaptor.MyViewHlder> {
private Activity activity;
private ArrayList<DataModel> list;
private String SubCategoryUrl = "http://philiabeauty.com/reader-choice/controller-api.php?action=get_subcategory_by_category&id=";
private String Token = "&access_token=Ym9va19kZXRhaWxz";
private String imgRoot = "http://philiabeauty.com/reader-choice/";
private String subCatId, subCatTitle, subCatImage;
public CategoryAdaptor(Activity activity, ArrayList<DataModel> list) {
this.activity = activity;
this.list = list;
}
#NonNull
#Override
public MyViewHlder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.category_list_layout, viewGroup, false);
MyViewHlder my = new MyViewHlder(view);
return my;
}
#Override
public void onBindViewHolder(#NonNull MyViewHlder myViewHlder, int i) {
final DataModel model = list.get(i);
myViewHlder.catText.setText(model.getTITLE());
myViewHlder.catId.setText(model.getID());
getSubCategory(myViewHlder,model.getID());
}
#Override
public int getItemCount() {
return list.size();
}
public void getSubCategory(MyViewHlder myViewHlder,String ID) {
String SubCategoryUrlFinal = SubCategoryUrl + ID + Token;
StringRequest stringRequest = new StringRequest(Request.Method.GET, SubCategoryUrlFinal, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
JSONArray jsonArray = obj.getJSONArray("DATA");
Log.v("SubCat Response", response.toString());
for (int i = 0; i < 3; i++) {
SubCatModel Model = new SubCatModel();
JSONObject jsonObject = jsonArray.getJSONObject(i);
subCatId = jsonObject.getString("ID");
subCatTitle = jsonObject.getString("TITLE");
subCatImage = imgRoot + jsonObject.getString("IMG_SRC");
Model.setSubCatIMG(subCatImage);
Model.setSubCatTITLE(subCatTitle);
Model.setSubCatID(subCatId);
myViewHlder.subCatList.add(Model);
}
myViewHlder.subcategoryAdaptor.notifyDataSetChanged();
} catch (JSONException e) {
System.out.print("Exception is :" + e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(activity);
requestQueue.add(stringRequest);
}
class MyViewHlder extends RecyclerView.ViewHolder {
private TextView catText, viewAllBtn, catId, tag;
private RecyclerView recyclerviewSubCat;
private SubCategoryAdaptor subcategoryAdaptor;
private ArrayList<SubCatModel> subCatList = new ArrayList<>();
public MyViewHlder(#NonNull View itemView) {
super(itemView);
catText = itemView.findViewById(R.id.cat_name);
viewAllBtn = itemView.findViewById(R.id.viewAllBtn);
catId = itemView.findViewById(R.id.cat_id);
recyclerviewSubCat = itemView.findViewById(R.id.recyclerviewSubCat);
LinearLayoutManager gridLayoutManager = new LinearLayoutManager(activity, LinearLayout.HORIZONTAL, false);
recyclerviewSubCat.setLayoutManager(gridLayoutManager); // set LayoutManager to RecyclerView
// call the constructor of CustomAdapter to send the reference and data to Adapter
subcategoryAdaptor = new SubCategoryAdaptor(activity, subCatList);
recyclerviewSubCat.setAdapter(subcategoryAdaptor);
}
}
}
Related
here getItemCount() not null, but here getlayoutmanager is null. plz help me to solved this. i'm trying to loadmore data when user scroll down recyclerview at end of scrolling load another data so on. This Error occurred in adapter.
here getLayoutManager() is get null:
final GridLayoutManager gridLayoutManager = (GridLayoutManager) recyclerView.getLayoutManager();
My Adapter code:
public class ImageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context mCtx;
private ImageView link;
private boolean isLoading;
private List<Image> imageList;
private int visibleThreshold = 5;
private final int VIEW_TYPE_ITEM = 0;
private final int VIEW_TYPE_LOADING = 1;
private int lastVisibleItem, totalItemCount;
private OnLoadMoreListener onLoadMoreListener;
public ImageAdapter(RecyclerView recyclerView, List<Image> imageList, Context mCtx) {
this.imageList = imageList;
this.mCtx = mCtx;
final GridLayoutManager gridLayoutManager = (GridLayoutManager) recyclerView.getLayoutManager();
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
Log.d(TAG, "Tj_getItemCount" + getItemCount());
Log.d(TAG, "Tj_linearLayoutManager" + gridLayoutManager);
totalItemCount = gridLayoutManager.getItemCount();
lastVisibleItem = gridLayoutManager.findLastVisibleItemPosition();
if (!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
if (onLoadMoreListener != null) {
onLoadMoreListener.onLoadMore();
}
isLoading = true;
}
}
});
}
public void setOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener) {
this.onLoadMoreListener = mOnLoadMoreListener;
}
#Override
public int getItemViewType(int position) {
return imageList.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == VIEW_TYPE_ITEM) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View v = inflater.inflate(R.layout.list_items, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
} else if (viewType == VIEW_TYPE_LOADING) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_loading, parent, false);
LoadingViewHolder vh1 = new LoadingViewHolder(view);
return vh1;
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof ViewHolder) {
final Image image = imageList.get(position);
final String imgUrl = image.getThumb();
link.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), ViewImage.class);
intent.putExtra("URL", imgUrl);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
v.getContext().startActivity(intent);
}
});
Glide.with(mCtx).load(imgUrl).into(link);
} else if (holder instanceof LoadingViewHolder) {
LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
loadingViewHolder.progressBar.setIndeterminate(true);
}
}
#Override
public int getItemCount() {
return imageList == null ? 0 : imageList.size();
}
public void setLoaded() {
isLoading = false;
}
private class LoadingViewHolder extends RecyclerView.ViewHolder {
public ProgressBar progressBar;
LoadingViewHolder(View view) {
super(view);
progressBar = view.findViewById(R.id.progressBar1);
}
}
class ViewHolder extends RecyclerView.ViewHolder {
ViewHolder(View v) {
super(v);
link = v.findViewById(R.id.link);
}
}
}
My Activity code:
public class MainActivity extends AppCompatActivity {
//the URL having the json data https://api.unsplash.com/search/photos?query=canada&client_id=8b0a3f8ddb23f80f16303601c12664119e27c2d26a6fc7b43bcba68d5c35f73c
// private static final String JSON_URL = "https://api.unsplash.com/photos/random?count=25&client_id=8b0a3f8ddb23f80f16303601c12664119e27c2d26a6fc7b43bcba68d5c35f73c";
// private static final String JSON_URL = "https://api.unsplash.com/photos/?client_id=8b0a3f8ddb23f80f16303601c12664119e27c2d26a6fc7b43bcba68d5c35f73c";
int i = 2;
Image hero;
String query;
List<Image> imageList;
RecyclerView listView;
private static String JSON_URL;
private static final String TAG = "Tj";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//initializing listview and hero list
listView = findViewById(R.id.listView);
imageList = new ArrayList<>();
Intent intent = getIntent();
query = intent.getStringExtra("category");
JSON_URL = "https://api.unsplash.com/search/photos?query=" + query + "&client_id=8b0a3f8ddb23f80f16303601c12664119e27c2d26a6fc7b43bcba68d5c35f73c&page=1";
Log.d(TAG, "Query" + JSON_URL);
loadHeroList();
}
private void loadHeroList() {
//getting the progressbar
final ProgressBar progressBar = findViewById(R.id.progressBar);
//making the progressbar visible
progressBar.setVisibility(View.VISIBLE);
//creating a string request to send request to the url
StringRequest jsonArrayRequest = new StringRequest(Request.Method.GET, JSON_URL,
new Response.Listener<String>() {
// JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
// Request.Method.GET,
// JSON_URL,
// null,
// new Response.Listener<JSONArray>() {
#Override
public void onResponse(String response) {
//hiding the progressbar after completion
progressBar.setVisibility(View.INVISIBLE);
try {
//getting the whole json object from the response
JSONObject obj = new JSONObject(response);
//we have the array named hero inside the object
//so here we are getting that json array
JSONArray heroArray = obj.getJSONArray("results");
//now looping through all the elements of the json array
for (int i = 0; i < heroArray.length(); i++) {
//getting the json object of the particular index inside the array
JSONObject jsonObject = heroArray.getJSONObject(i);
JSONObject jsonObject1 = jsonObject.getJSONObject("urls");
//creating a hero object and giving them the values from json object
hero = new Image(jsonObject.getString("id"),
jsonObject.getString("color"),
jsonObject1.getString("full"));
//adding the hero to herolist
imageList.add(hero);
}
//creating custom adapter object
final ImageAdapter adapter = new ImageAdapter(listView, imageList, getApplicationContext());
listView.setHasFixedSize(true);
// use a grid layout manager
listView.setLayoutManager(new GridLayoutManager(MainActivity.this, 2));
//adding the adapter to listview
listView.setAdapter(adapter);
adapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
if (imageList.size() <= 20) {
imageList.add(null);
adapter.notifyItemInserted(imageList.size() - 1);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
imageList.remove(imageList.size() - 1);
adapter.notifyItemRemoved(imageList.size());
JSON_URL = "https://api.unsplash.com/search/photos?query=" + query + "&client_id=8b0a3f8ddb23f80f16303601c12664119e27c2d26a6fc7b43bcba68d5c35f73c&page=" + i;
Log.d(TAG, "QueryLoadMore" + JSON_URL);
i++;
StringRequest jsonArrayRequest = new StringRequest(Request.Method.GET, JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//hiding the progressbar after completion
progressBar.setVisibility(View.INVISIBLE);
try {
//getting the whole json object from the response
JSONObject obj = new JSONObject(response);
//we have the array named hero inside the object
//so here we are getting that json array
JSONArray heroArray = obj.getJSONArray("results");
//now looping through all the elements of the json array
for (int i = 0; i < heroArray.length(); i++) {
//getting the json object of the particular index inside the array
JSONObject jsonObject = heroArray.getJSONObject(i);
JSONObject jsonObject1 = jsonObject.getJSONObject("urls");
//creating a hero object and giving them the values from json object
hero = new Image(jsonObject.getString("id"),
jsonObject.getString("color"),
jsonObject1.getString("full"));
//adding the hero to herolist
imageList.add(hero);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
//adding the string request to request queue
requestQueue.add(jsonArrayRequest);
// imageList.add(hero);
// }
adapter.notifyDataSetChanged();
adapter.setLoaded();
}
}, 5000);
} else {
Toast.makeText(MainActivity.this, "Loading data completed", Toast.LENGTH_SHORT).show();
}
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//adding the string request to request queue
requestQueue.add(jsonArrayRequest);
}
}
You never set any kind of LayoutManager to your listView.
You must set the layout manager before creating your custom adapter object.
You can set it by calling: recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns)); Then you are able to get it later in your ImageAdapter class.
I have a fragment, the name is galery. in the fragment galery i'll showing a recycleView that contains name list. but i find an error in this script :
LinearLayoutManager llm = new LinearLayoutManager(this);
and this my full code :
public class galery extends Fragment {
private RecyclerView lvhape;
private RequestQueue requestQueue;
private StringRequest stringRequest;
ArrayList<HashMap<String, String>> list_data;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_galery, container, false);
String url = "http://bls.hol.es/read.php";
lvhape = (RecyclerView) rootView.findViewById(R.id.lvhape);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
lvhape.setLayoutManager(llm);
requestQueue = Volley.newRequestQueue(galery.this);
list_data = new ArrayList<HashMap<String, String>>();
stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response", response);
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("result");
for (int a = 0; a < jsonArray.length(); a++) {
JSONObject json = jsonArray.getJSONObject(a);
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", json.getString("id"));
map.put("nama", json.getString("nama"));
map.put("alamat", json.getString("alamat"));
map.put("poto", json.getString("poto"));
list_data.add(map);
AdapterList adapter = new AdapterList(galery.this, list_data);
lvhape.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(stringRequest);
return rootView;
}
}
Try This On Fragment Create Adapter And Model Class And RecyclerView in .xml Class.
public class Event extends Fragment {
RecyclerView recyclerView;
private Event_Adapter event_adapter;
public Event_Model event_model;
public static List<Event_Model> list;
RecyclerView.LayoutManager mLayoutManager;
private static final String FETCH_ID = "id";
private static final String FETCH_NAME = "event_type";
private static final String FETCH_MOBILE = "contact";
private static final String FETCH_DATE = "date";
private static final String FETCH_IMAGE = "uri";
public static final String FETCH_DETAIL = "Your Url";
String type,number,date,uri,id;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.fragment_event, container, false);
list = new ArrayList<Event_Model>();
recyclerView = (RecyclerView) v.findViewById(R.id.event_recycler);
mLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(mLayoutManager);
fetchdetails();
return v;
}
private void fetchdetails(){
StringRequest jor = new StringRequest(Request.Method.POST, FETCH_DETAIL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
/* Toast.makeText(getActivity(),response,Toast.LENGTH_LONG).show();*/
try {
JSONArray ja = new JSONArray(response);
for (int i = 0; i < ja.length(); i++) {
JSONObject jsonObject = ja.getJSONObject(i);
Integer.parseInt(jsonObject.optString("id").toString());
type = jsonObject.getString(FETCH_NAME);
number = jsonObject.getString(FETCH_MOBILE);
date = jsonObject.getString(FETCH_DATE);
uri = jsonObject.getString(FETCH_IMAGE);
id = jsonObject.getString(FETCH_ID);
event_model = new Event_Model(type,number,date,uri,id);
list.add(event_model);
}
} catch (JSONException e) {
e.printStackTrace();
}
event_adapter= new Event_Adapter(getActivity(), list);
recyclerView.setAdapter(event_adapter);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
}
);
RetryPolicy retryPolicy=new DefaultRetryPolicy(60000,0,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
jor.setRetryPolicy(retryPolicy);
VolleySingleton.getInstance(getActivity()).addToRequestQueue(jor);
}
}
I did some changes it works fine in my app try it and if any error occurred mention in comment.
public class GalaryFragment extends Fragment {
private RecyclerView recyclerView;
private List<ProductModel> list1;
private ProductModel productMode;
private ProductAdapter productAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.frament_galary, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
String url = "http://bls.hol.es/read.php";
mRecyclerView = (RecyclerView) view.findViewById(R.id.lvhape);
list1 = new ArrayList<>();
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
cashbackAdapter = new ProductAdapter(getActivity(), list1);
mRecyclerView2.setAdapter(productAdapter);
final ProgressDialog dialog = new ProgressDialog(getActivity());
dialog.setMessage("Loading......");
dialog.show();
StringRequest stringRequest = new StringRequest(Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Toast.makeText(getActivity(),response+"",Toast.LENGTH_LONG).show();
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String id = jsonObject.getString("id");
String name = jsonObject.getString("name");
String image = jsonObject.getString("image");
productModel = new ProductModel(id, name, image);
list1.add(productModel);
}
productAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
});
VolleySingleton.getInstance(getActivity()).addToRequestQueue(stringRequest);
}
}
ProductAdapter code:
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.MyViewHolder> {
private List<ProductModel> list;
private Context mContext;
public ProductAdapter(Context mContext, List<ProductModel> list) {
this.mContext = mContext;
this.list=list;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_galary, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
final ProductModel productModel=list.get(position);
holder.name.setText(productModel.getName());
Picasso.with(mContext)
.load(productModel.getImage())
.placeholder(R.mipmap.ic_launcher)
.error(R.mipmap.ic_launcher)
.into(holder.iv);
}
#Override
public int getItemCount() {
return list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public ImageView iv;
public MyViewHolder(View view) {
super(view);
name = (TextView) view.findViewById(R.id.name);
iv = (ImageView) view.findViewById(R.id.image);
}
}
}
PoductModel code:
public class ProductModel {
String id;
String name;
String image;
public nameModel(String id, String name, String image) {
this.id = id;
this.name = name;
this.image = image;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getname() {
return name;
}
public void setname(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
VolleySingleton class:
public class VolleySingleton {
private static VolleySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;
private VolleySingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
mImageLoader = new ImageLoader(mRequestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static synchronized VolleySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new VolleySingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
public ImageLoader getImageLoader() {
return mImageLoader;
}
}
try this
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_galery, container, false);
String url = "http://bls.hol.es/read.php";
lvhape = (RecyclerView) getView().findViewById(R.id.lvhape);
LinearLayoutManager llm = new LinearLayoutManager(gallary.getContext());
llm.setOrientation(LinearLayoutManager.VERTICAL);
lvhape.setLayoutManager(llm);
requestQueue = Volley.newRequestQueue(galery.this);
list_data = new ArrayList<HashMap<String, String>>();
stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response", response);
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("result");
for (int a = 0; a < jsonArray.length(); a++) {
JSONObject json = jsonArray.getJSONObject(a);
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", json.getString("id"));
map.put("nama", json.getString("nama"));
map.put("alamat", json.getString("alamat"));
map.put("poto", json.getString("poto"));
list_data.add(map);
AdapterList adapter = new AdapterList(galery.this, list_data);
lvhape.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(stringRequest);
return rootView;
}
onCreate() will be called before onCreateView() methods so getView() will return null
Try like this
public class galery extends Fragment {
private RecyclerView lvhape;
private RequestQueue requestQueue;
private StringRequest stringRequest;
ArrayList<HashMap<String, String>> list_data;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_galery, container, false);
return rootView;
}
public void onViewCreated(View view, Bundle savedInstanceState) {
String url = "http://bls.hol.es/read.php";
lvhape = (RecyclerView) view.findViewById(R.id.lvhape);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
lvhape.setLayoutManager(llm);
requestQueue = Volley.newRequestQueue(getActivity());
list_data = new ArrayList<HashMap<String, String>>();
stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response", response);
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("result");
for (int a = 0; a < jsonArray.length(); a++) {
JSONObject json = jsonArray.getJSONObject(a);
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", json.getString("id"));
map.put("nama", json.getString("nama"));
map.put("alamat", json.getString("alamat"));
map.put("poto", json.getString("poto"));
list_data.add(map);
AdapterList adapter = new AdapterList(galery.this, list_data);
lvhape.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(stringRequest);
}
i have a series of items in recyclerview .i want to set on click listener and open a description page of specific item and set data from json url. i have already made an adapter for description screen and a bean class. i dont know how to set adapter on layout. is it possible to set an adapter on linear layout to show static content from json url?
My code is :
Description activity
private class MakeRequestForGetDescription extends AsyncTask<String, Void, String> {
ProgressDialog Pdialog;
private String response;
private MakeServiceClass makeServiceClass = new MakeServiceClass();
#Override
protected void onPreExecute() {
Pdialog = new ProgressDialog(getActivity());
Pdialog.setMessage("Please Wait..");
Pdialog.show();
}
#Override
protected String doInBackground(String... params) {
try {
HashMap<String, String> parms = new HashMap<String, String>();
response = makeServiceClass.makeServiceConnectionGet(ConstUrl.DESCRP_URLS);
Log.e("response ads", response);
} catch (Exception ex) {
ex.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(response);
if (Pdialog != null) {
Pdialog.dismiss();
}
if (response != null) {
try {
JSONObject mainObject = new JSONObject(response);
if (mainObject.has("status")) {
String Status = mainObject.getString("status");
String img_url = "";
if (Status.equalsIgnoreCase("200")) {
if (mainObject.has("img_url")) {
img_url = mainObject.getString("img_url");
Log.e("img_url", img_url);
}
if (mainObject.has("details")) {
JSONArray datArray = mainObject.getJSONArray("details");
descriptionBeanArrayList = new ArrayList<>();
if (datArray.length() > 0) {
for (int i = 0; i < datArray.length(); i++) {
DescriptionBean descriptionBean = new DescriptionBean();
JSONObject internalDataObject = datArray.getJSONObject(i);
if (internalDataObject.has("id")) {
descriptionBean.setId(internalDataObject.getString("id"));
}
if (internalDataObject.has("title_en")) {
descriptionBean.setTitle_en(internalDataObject.getString("title_en"));
}
if (internalDataObject.has("ad_description_en")) {
descriptionBean.setAd_description_en(internalDataObject.getString("ad_description_en"));
}
if (internalDataObject.has("price")) {
descriptionBean.setPrice(internalDataObject.getString("price"));
}
if (internalDataObject.has("km_driven")) {
descriptionBean.setKm_driven(internalDataObject.getString("km_driven"));
}
if (internalDataObject.has("image_file")) {
descriptionBean.setImage_file("http://" + img_url + internalDataObject.getString("image_file"));
}
descriptionBeanArrayList.add(descriptionBean);
}
setAdapterForDescription();
}
}
} else {
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void setAdapterForDescription() {
DescriptionAdapter adapter = new DescriptionAdapter(getActivity(), descriptionBeanArrayList);
}
}
Description Adapter
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(R.layout.fragment_description, parent,false);
viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
viewHolder.tvRate = (TextView) convertView.findViewById(R.id.tvRate);
viewHolder.tvMiles = (TextView) convertView.findViewById(R.id.tvMiles);
viewHolder.et_description = (EditText) convertView.findViewById(R.id.et_description);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
//setdata
viewHolder.tvTitle.setText(descriptionBeanArrayList.get(position).getTitle_en());
viewHolder.tvRate.setText(descriptionBeanArrayList.get(position).getPrice());
viewHolder.tvMiles.setText(descriptionBeanArrayList.get(position).getKm_driven());
viewHolder.et_description.setText(descriptionBeanArrayList.get(position).getAd_description_en());
Log.e("s", descriptionBeanArrayList.get(position).getImage_file());
//Glide.with(mContext).load("www.apnikheti.com/upload/buysell/idea99A4.jpg").into(viewHolder.iv_picofproduct);
Picasso.with(mContext).load(descriptionBeanArrayList.get(position).getImage_file()).into(viewHolder.iv_picofproduct, new Callback() {
#Override
public void onSuccess() {
Log.e("s", "sucess");
}
#Override
public void onError() {
Log.e("s", "failed");
}
});
Picasso.with(mContext).setLoggingEnabled(true);
return convertView;
}
public class ViewHolder {
private TextView tvTitle,tvRate,tvMiles;
private EditText et_description;
public ImageView iv_picofproduct;
}
}
This is my code which is used to retrieve data from url (Json Data) and load it into a recyclerview using adapter and passing the same values to another activity.
MyActivity
public class Video_List extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
//private GridLayoutManager layoutManager;
private List<Video_Details> videodetails;
public static final String VideoID = "v_id";
public static final String ID = "id";
public static final String Title = "title";
public static final String Thumb = "thumb";
public static final String url = "http://115.115.122.10/paul/api/videos.php?start=1&count=10";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video__list);
getdata();
recyclerView = (RecyclerView) findViewById(R.id.card_recycler_view);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
//layoutManager = new GridLayoutManager(this,2);
recyclerView.setLayoutManager(layoutManager);
videodetails = new ArrayList<>();
}
private void getdata(){
final ProgressDialog loading = ProgressDialog.show(this,"Loading Data", "Please wait...",false,false);
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Dismissing progress dialog
loading.dismiss();
Log.d("count",response.toString());
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.dismiss();
Log.d("infoz","777"+error.getMessage());
Toast.makeText(getApplicationContext(),"No data Found",Toast.LENGTH_LONG).show();
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
//This method will parse json data
private void parseData(JSONArray array){
try {
for (int i = 0; i < array.length(); i++) {
JSONObject json = array.getJSONObject(i);
Video_Details video = new Video_Details();
if (json.has(VideoID)) {
Log.d("has values", json.getString(VideoID));
}
video.setId(json.getString(ID));
video.setV_id(json.getString(VideoID));
video.setTitle(json.getString(Title));
video.setThumb(json.getString(VideoID));
videodetails.add(video);
if (json.has(VideoID))
{
Log.d("Video",VideoID);
}
}
} catch (Exception e) {
e.printStackTrace();
}
//Finally initializing our adapter
adapter = new DataAdapter(videodetails, this);
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
}
}
MyAdapter
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private Context context;
List<Video_Details> video;
public DataAdapter(List<Video_Details> video, Context context) {
super();
this.context = context;
this.video = video;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_row, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final Video_Details videoDetails = video.get(position);
String url;
final String VideoID;
holder.title.setText(video.get(position).getTitle());
VideoID= video.get(position).getV_id();
url = video.get(position).getThumb();
Glide.with(context)
.load(url)
.override(150,70)
.into(holder.thumb);
//viewHolder.thumb.setText(android.get(i).getVer());
// viewHolder.tv_api_level.setText(android.get(i).getApi());
holder.vm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "You Clicked"+video.get(position).getV_id(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(v.getContext(),Play_Video.class);
intent.putExtra("VideoId",(video.get(position).getV_id()));
intent.putExtra("Title",(video.get(position).getTitle()));
v.getContext().startActivity(intent);
}
}
);
}
#Override
public int getItemCount() {
return video.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView title;
public ImageView thumb;
public String videoid;
public View vm;
public ViewHolder(View view) {
super(view);
vm = view;
title = (TextView)view.findViewById(R.id.title);
thumb = (ImageView) view.findViewById(R.id.thumb);
//tv_version = (TextView)view.findViewById(R.id.tv_version);
//tv_api_level = (TextView)view.findViewById(R.id.tv_api_level);
}
}
}
I have responsed JSONObject from API and i tried to send the response to the module using setter then to the Recyclerview adapter but its not working
This is my fragment
public class ListViewActivityFragment extends Fragment {
List<AppShowModule> appShowModule;
RecyclerView AppRecyclerView;
List<AppShowModule> GetDataAdapter1;
RecyclerView.LayoutManager AppRecyclerViewlayoutManager;
RecyclerView.Adapter AppRecyclerViewadapter;
String jsonUrl = "https://itunes.apple.com/jo/rss/topfreeapplications/limit=50/json";
TextView text;
Context context;
RequestQueue requestQueue;
public ListViewActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_list_view, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
appShowModule = new ArrayList<>();
AppRecyclerView = (RecyclerView) getView().findViewById( R.id.AppRecyclerView );
text = (TextView) getView().findViewById(R.id.textView2);
AppRecyclerView.setHasFixedSize( true );
GetDataAdapter1 = new ArrayList<>();
AppRecyclerView.setLayoutManager( AppRecyclerViewlayoutManager );
JsonAppShowData();}
public void JsonAppShowData() {
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest( jsonUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONObject("feed").getJSONArray( "entry" );
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json1 = jsonArray.getJSONObject( i ).getJSONObject("im:name");
AppShowModule appShowModule111 = new AppShowModule();
String name = response.getJSONObject("feed").getJSONArray("entry").getJSONObject(i).getJSONObject("im:name").getString("label").toString();
text.setText(name);
appShowModule111.setAppName((name));}
} catch (JSONException e) {
e.printStackTrace();
}}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e( "LOG", error.toString() );
}
} );
requestQueue = Volley.newRequestQueue( getContext() );
requestQueue.add(jsonObjectRequest);
AppRecyclerView.setLayoutManager(new LinearLayoutManager(context));
AppRecyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1,this);
AppRecyclerView.setAdapter(AppRecyclerViewadapter);
}
}
and this is my adapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
List<AppShowModule> getDataAdapter;
Context MContext;
public RecyclerViewAdapter(List<AppShowModule> getDataAdapter, ListViewActivityFragment context){
super();
this.getDataAdapter = getDataAdapter;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.appitem, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position)
{
final AppShowModule getDataAdapter1 = getDataAdapter.get(position);
holder.NameTextView.setText(getDataAdapter1.getAppName());
Picasso.with(context).load(getDataAdapter1.getAppImageUrl()).into(holder.imgPost);
}
#Override
public int getItemCount() {
return getDataAdapter.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView NameTextView;
public ImageView imgPost;
LinearLayout lnrLayout;
public ViewHolder(View itemView) {
super(itemView);
NameTextView = (TextView) itemView.findViewById(R.id.appName);
imgPost = (ImageView) itemView.findViewById(R.id.appImage);
lnrLayout = (LinearLayout)itemView.findViewById(R.id.lnrLayout);
}
}
}
and this is my module
public class AppShowModule
{
private String appName;
private String appImageUrl;
public String getAppName() {
return appName;}
public void setAppName(String appName) {
this.appName = appName;}
public String getAppImageUrl() {
return appImageUrl;}
public void setAppImageUrl(String appImageUrl) {
this.appImageUrl = appImageUrl;}
}
Yo are creating the AppShowModule appShowModule111 = new AppShowModule(); Object but you never populated your adaapter with that object. Your JsonObjectRequest onResponse() should look like this;
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONObject("feed").getJSONArray( "entry" );
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json1 = jsonArray.getJSONObject( i ).getJSONObject("im:name");
AppShowModule appShowModule111 = new AppShowModule();
String name = response.getJSONObject("feed").getJSONArray("entry").getJSONObject(i).getJSONObject("im:name").getString("label").toString();
text.setText(name);
appShowModule111.setAppName((name));
GetDataAdapter1.add(appShowModule111);
}
AppRecyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1,ListViewActivityFragment.this);
AppRecyclerView.setAdapter(AppRecyclerViewadapter);
} catch (JSONException e) {
e.printStackTrace();
}}
I've a recyclerview adapter with 3 textviews. I used a model class to set texts. Now I want to use the same adapter with different layout and in a different class which only have 1 textview. When I tried, I got NullPointerException (may be becuz the other 2 textviews are blank). Is there any way to use same adapter with different layout and in different class?
// second class - I used 1 textview
public class Customers extends AppCompatActivity{
private CShowProgress cShowProgress;
private RecyclerView mRecyclerView;
private TimeLineAdapter mTimeLineAdapter;
private List<TimeLineModel> mDataList = new ArrayList<>();
private static final String CUSTOMERS = "http://192.168.200.3/ubooktoday/android/showspacustomerlist";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.customers);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
cShowProgress = CShowProgress.getInstance();
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(getLinearLayoutManager());
mRecyclerView.setHasFixedSize(true);
showCustomers();
}
private void showCustomers() {
if(mDataList!=null )mDataList.clear();
cShowProgress.showProgress(Customers.this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, CUSTOMERS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
cShowProgress.hideProgress();
try {
JSONArray jsonArray = new JSONArray(response);
for(int i=0; i<jsonArray.length(); i++){
JSONObject obj = jsonArray.getJSONObject(i);
TimeLineModel model = new TimeLineModel();
model.setCustname(obj.getString("customername"));
mDataList.add(model);
mTimeLineAdapter = new TimeLineAdapter(getApplicationContext(), R.layout.item_row_customer, mDataList);
mRecyclerView.setAdapter(mTimeLineAdapter);
}
mTimeLineAdapter.notifyDataSetChanged();
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "VolleyError" + error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("spaid", "145");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
private LinearLayoutManager getLinearLayoutManager() {
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
return linearLayoutManager;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
}
return true;
}
}
// first class - I used all 3 textviews
public class Walkin extends Fragment{
private RecyclerView mRecyclerView;
private TimeLineAdapter mTimeLineAdapter;
private List<TimeLineModel> mDataList = new ArrayList<>();
private static final String DASHBOARD = "My API";
#Nullable
#Override
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.walkin, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(getLinearLayoutManager());
mRecyclerView.setHasFixedSize(true);
showDashboard();
}
private void showDashboard() {
if(mDataList!=null )mDataList.clear();
cShowProgress.showProgress(getActivity());
StringRequest stringRequest = new StringRequest(Request.Method.POST, DASHBOARD,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("walkinlist");
for(int i=0; i<jsonArray.length(); i++){
JSONObject obj = jsonArray.getJSONObject(i);
TimeLineModel model = new TimeLineModel();
model.setCustname(obj.getString("customername"));
model.setTime(obj.getString("serviceDuration"));
model.setServname(obj.getString("service"));
mDataList.add(model);
mTimeLineAdapter = new TimeLineAdapter(getActivity(), R.layout.item_row_dashboard, mDataList);
mRecyclerView.setAdapter(mTimeLineAdapter);
}
mTimeLineAdapter.notifyDataSetChanged();
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getActivity(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "VolleyError" + error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("spaid", "145");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
private LinearLayoutManager getLinearLayoutManager() {
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
return linearLayoutManager;
}
}
// Adapter class
public class TimeLineAdapter extends RecyclerView.Adapter<TimeLineViewHolder> {
private List<TimeLineModel> mFeedList;
int resource;
private Context mContext;
public TimeLineAdapter(Context mContext, int resource, List<TimeLineModel> feedList) {
this.resource = resource;
this.mContext = mContext;
mFeedList = feedList;
}
#Override
public TimeLineViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = View.inflate(parent.getContext(), resource, null);
return new TimeLineViewHolder(view, viewType);
}
#Override
public void onBindViewHolder(TimeLineViewHolder holder, int position) {
TimeLineModel timeLineModel = mFeedList.get(position);
holder.servicename.setText(timeLineModel.getServname());
holder.custname.setText(timeLineModel.getCustname());
holder.time.setText(timeLineModel.getTime());
}
#Override
public int getItemCount() {
return (mFeedList!=null? mFeedList.size():0);
}
}
// ViewHolder class
public class TimeLineViewHolder extends RecyclerView.ViewHolder {
public TextView servicename, custname, time;
public TimeLineViewHolder(View itemView, int viewType) {
super(itemView);
servicename = (TextView) itemView.findViewById(R.id.tv_service);
custname = (TextView) itemView.findViewById(R.id.tv_cust);
time = (TextView) itemView.findViewById(R.id.tv_time);
}
}
You can use the getItemViewType().
Make your adapter(here TimeLineAdapter) extend RecyclerView.Adapter only.
You can change the Adapter's constructer to recieve ItemType and use it in the getItemViewType
Override the int getItemViewType (int position) method in your adapter.
In the onCreateViewHolder you can differentiate between which layout you want to inflate by using the viewType parameter.
In onBindViewHolder use instanceof to check which ViewHolder was created and call the related bind functions
A Sample Code-
// Adapter class
public class TimeLineAdapter extends RecyclerView.Adapter{
.....
int type;
public TimeLineAdapter(Context mContext, int resource, List<TimeLineModel> feedList,int layoutType) {
.....
.....
type=layoutType;
}
#Override
public int getItemViewType(int position) {
return type;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType==1){
View view = View.inflate(parent.getContext(), resource, null);
return new TimeLineViewHolder(view, viewType);
}else{
View view = View.inflate(parent.getContext(), resource, null);
return new TimeLineViewHolder2(view, viewType);
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if(holder instanceof TimeLineViewHolder){
TimeLineModel timeLineModel = mFeedList.get(position);
((TimeLineViewHolder) holder).servicename.setText(timeLineModel.getServname());
......
}
else if(holder instanceof TimeLineViewHolder2){
....
....
}
}
#Override
public int getItemCount() {
return (mFeedList!=null? mFeedList.size():0);
}
}