How to display inner json array in recyclerview android - android

I want to show inner json array in Recyclerview.
I was getting all the data in logcat.
But my problem is how to write code in adapter class for inner array items.
My problem is like this question
How to get data from nested json array android
I have similar json array.
I want to pass arraylist to Adapter.
This is my modal
public class OuterModal {
String menuId;
String menuName;
private List<InnerModal> innerItem;
public String getMenuId() {
return menuId;
}
public void setMenuId(String menuId) {
this.menuId = menuId;
}
public String getMenuName() {
return menuName;
}
public void setMenuName(String menuName) {
this.menuName = menuName;
}
public List<InnerModal> getInnerItem() {
return innerItem;
}
public void setInnerItem(List<InnerModal> innerItem) {
this.innerItem = innerItem;
}
}
This is my another modal
public class InnerModal {
String vendor_item_id;
String vendor_id;
String vendor_item_name;
String vendor_item_image;
String vendor_item_price;
String vendor_item_category;
String vendor_item_description;
String vendor_item_status;
public String getVendor_item_id() {
return vendor_item_id;
}
public void setVendor_item_id(String vendor_item_id) {
this.vendor_item_id = vendor_item_id;
}
public String getVendor_id() {
return vendor_id;
}
public void setVendor_id(String vendor_id) {
this.vendor_id = vendor_id;
}
public String getVendor_item_name() {
return vendor_item_name;
}
public void setVendor_item_name(String vendor_item_name) {
this.vendor_item_name = vendor_item_name;
}
public String getVendor_item_image() {
return vendor_item_image;
}
public void setVendor_item_image(String vendor_item_image) {
this.vendor_item_image = vendor_item_image;
}
public String getVendor_item_price() {
return vendor_item_price;
}
public void setVendor_item_price(String vendor_item_price) {
this.vendor_item_price = vendor_item_price;
}
public String getVendor_item_category() {
return vendor_item_category;
}
public void setVendor_item_category(String vendor_item_category) {
this.vendor_item_category = vendor_item_category;
}
public String getVendor_item_description() {
return vendor_item_description;
}
public void setVendor_item_description(String vendor_item_description) {
this.vendor_item_description = vendor_item_description;
}
public String getVendor_item_status() {
return vendor_item_status;
}
public void setVendor_item_status(String vendor_item_status) {
this.vendor_item_status = vendor_item_status;
}
}
This is JSON Responce
StringRequest stringRequest = new StringRequest(Request.Method.GET,
mainUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("menu");
List<OuterModal> outerModalList=new ArrayList<>();
OuterModal outerModal=new OuterModal();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
String menu_id = json.getString("menu_id");
String menu_name = json.getString("menu_name");
outerModal.setMenuId(menu_id);
outerModal.setMenuName(menu_name);
JSONArray productsListArray = json.getJSONArray("Products List");
for (int j = 0; j < productsListArray.length(); j++) {
// Log.d("myDraaa", "list responce:" + productsListArray);
JSONObject productsListjson = productsListArray.getJSONObject(j);
InnerModal innerModal=new InnerModal();
List<InnerModal> innerModalList=new ArrayList<>();
String vendor_item_id = productsListjson.getString("vendor_item_id");
String vendor_id = productsListjson.getString("vendor_id");
String vendor_item_name = productsListjson.getString("vendor_item_name");
String vendor_item_image = productsListjson.getString("vendor_item_image");
String vendor_item_status = productsListjson.getString("vendor_item_status");
String quantity = productsListjson.getString("quantity");
innerModal.setVendor_id(vendor_id);
innerModal.setVendor_item_id(vendor_item_id);
innerModal.setVendor_item_category("");
innerModal.setVendor_item_description("");
innerModal.setVendor_item_image(vendor_item_image);
innerModal.setVendor_item_name(vendor_item_name);
innerModal.setVendor_item_status(vendor_item_status);
innerModal.setVendor_item_price(quantity);
outerModal.getInnerItem().add(innerModal);
}
outerModalList.add(outerModal);
}
public class SecondAdapter extends RecyclerView.Adapter<SecondAdapter.SecondVH> {
List<OuterModal> arrayList;
Context context;
public SecondAdapter(List<OuterModal> arrayList, Context context) {
this.arrayList = arrayList;
this.context = context;
}
#NonNull
#Override
public SecondVH onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.my_custom_style, null, false);
return new SecondVH(v);
}
#Override
public void onBindViewHolder(#NonNull SecondVH holder, final int position) {
OuterModal outerModal=arrayList.get(position);
holder.title.setText(outerModal.getMenuName());
}
#Override
public int getItemCount() {
return arrayList.size();
}
public class SecondVH extends RecyclerView.ViewHolder {
TextView title;
TextView items;
ConstraintLayout constraintLayout;
TextView itemName, itemPrice, itemDescription;
public SecondVH(View itemView) {
super(itemView);
title = itemView.findViewById(R.id.bestSellers);
items = itemView.findViewById(R.id.myCustItemName);
constraintLayout = itemView.findViewById(R.id.csL);
itemPrice = itemView.findViewById(R.id.itemPrice);
itemDescription = itemView.findViewById(R.id.itemDesc);
}
}
}
Thanks in advance.
Please help me.

Related

How to get size of a particular variable from Model class in Android?

I have a model class:
public class Home_Model_ViewPager {
public String buttonLink;
public String tipsDescription;
public String tipsButton;
public Context context;
public Home_Model_ViewPager( Context context, String tipsDescription, String tipsButton, String buttonLink) {
this.context = context;
this.tipsDescription = tipsDescription;
this.tipsButton = tipsButton;
this.buttonLink = buttonLink;
}
public String getButtonLink() {
return buttonLink;
}
public void setButtonLink(String buttonLink) {
this.buttonLink = buttonLink;
}
public String getTipsDescription() {
return tipsDescription;
}
public void setTipsDescription(String tipsDescription) {
this.tipsDescription = tipsDescription;
}
public String getTipsButton() {
return tipsButton;
}
public void setTipsButton(String tipsButton) {
this.tipsButton = tipsButton;
}
}
I have used this model class to use it in viewpager adapter.
So, I am using a recyclerview and setting data to it. Now I have a problem that I have a viewpager in recycleritem. I want to return the size of viewpager adapter of any element in Home_Model_ViewPager as each element has diff size.
This is what I tried in ViewPagerAdapter:
public class ViewPagerAdapter extends PagerAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
List<Home_Model_ViewPager> totalList;
public ViewPagerAdapter(Context context, List<Home_Model_ViewPager> totalList) {
this.context = context;
this.totalList = totalList;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return totalList.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
// Declare Variables
TextView tricksDescription;
Button tricksButton;
View itemView = inflater.inflate(R.layout.viewpager_item, container,
false);
tricksDescription = itemView.findViewById(R.id.xtv_tricks_description);
tricksButton = itemView.findViewById(R.id.tricks_button);
tricksDescription.setText(Html.fromHtml(totalList.get(position).getTipsDescription()));
tricksButton.setText(Html.fromHtml(totalList.get(position).getTipsButton()));
tricksButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
String url = totalList.get(position).getButtonLink();
intent.setData(Uri.parse(url));
startActivity(intent);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
container.addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
I am using volley to get the values as JSON..
private void Home() {
try {
if (getActivity()!=null)
Commonfunctions.LoadPreferences(getActivity());
System.out.println("Authtoken:" + Commonfunctions.Token_key);
appservice.View_All_Events(Commonfunctions.Token_key, String.valueOf(pagenumber), new Server_Callback() {
#Override
public void onSuccess(String response) {
System.out.println("HOME Response :" + response);
try {
JSONObject signObject = new JSONObject(response);
String resStatus = signObject.getString(AppConstants.STATUS);
String resCode = signObject.getString(AppConstants.CODE);
String resMsg = signObject.getString(AppConstants.MSG);
if (resCode.equals(AppConstants.SUCCESS_CODE)) {
JSONArray allEvents = signObject.getJSONArray("all");
System.out.println("INNER Response :" + allEvents);
for (int i = 0; i < allEvents.length(); i++) {
JSONObject innerObj1 = allEvents.getJSONObject(i);
String backgroundImg = innerObj1.getString("backg_img");
String declinedCount = innerObj1.getString("decli_count");
String acceptedCount = innerObj1.getString("accep_count");
String invitedCount = innerObj1.getString("invi_count");
String messages = innerObj1.getString("i_chat");
String name = innerObj1.getString("name");
String eventTime = innerObj1.getString("duration");
String userPhoto = innerObj1.getString("photo");
JSONArray viewpagerEvents = innerObj1.getJSONArray("action");
for (int u = 0; u < viewpagerEvents.length(); u++) {
JSONObject innerObj3 = viewpagerEvents.getJSONObject(u);
String buttonText = innerObj3.getString("text");
String tipsDesc = innerObj3.getString("action_text");
String buttonLink = innerObj3.getString("button_link");
final Home_Model home_data = new Home_Model(name, messages,invitedCount,declinedCount,acceptedCount,eventTime,
userPhoto,backgroundImg);
data.add(home_data);
final Home_Model_ViewPager home_viewpager = new Home_Model_ViewPager(getContext(),tipsDesc,buttonText, buttonLink);
viewPagerData.add(home_viewpager);
}
}
adapter = new HomeAdapter(getContext(),data);
pagerAdapter = new ViewPagerAdapter(getActivity(), viewPagerData);
home_recycler.setAdapter(adapter);
adapter.notifyDataSetChanged();
if (adapter.getItemCount()==0) {
noeventLayout.setVisibility(View.VISIBLE);
}
else {
noeventLayout.setVisibility(View.GONE);
}
} else if (resCode.equals(AppConstants.UPDATE_CODE)) {
//Version_Update versionUpdate=new Version_Update(SignIn.this,response);
} else {
getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
Commonfunctions.showerrorsnackbar(resMsg, getActivity(), parentLayout);
}
} catch (JSONException e) {
e.printStackTrace();
}
}//on success close
});//server callback closed
} catch (Exception e) {
e.printStackTrace();
}
}
HomeAdapter:
class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.ViewHolder> {
Context context;
List<Home_Model> students;
public HomeAdapter(Context context,List<Home_Model> students) {
this.context = context;
this.students = students;
}
#Override
public HomeAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.event_home_list, viewGroup, false);
return new HomeAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(final HomeAdapter.ViewHolder holder, final int position) {
holder.title.setText(students.get(position).getName());
holder.invited.setText(students.get(position).getInvited());
holder.accepted.setText(students.get(position).getAccept());
holder.declined.setText(students.get(position).getDecline());
holder.eventTime.setText(students.get(position).getEvent_time());
holder.messages.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getActivity(),Chat_view.class));
}
});
holder.viewPager.setAdapter(pagerAdapter);
holder.dots = new ImageView[holder.dotsCount];
for (int i = 0; i < holder.dotsCount; i++) {
holder.dots[i] = new ImageView(context);
holder.dots[i].setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_dot_gray ));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(8, 0, 8, 0);
holder.sliderDots.addView(holder.dots[i], params);
}
holder.dots[0].setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_dot_colorprimary));
holder.viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for (int i = 0; i < holder.dotsCount; i++) {
holder.dots[i].setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_dot_gray));
}
holder.dots[position].setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_dot_colorprimary));
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
if (students.get(position).getMessages().contentEquals("false")) {
holder.status.setVisibility(View.INVISIBLE);
}
else {
holder.status.setVisibility(View.VISIBLE);
}
holder.status.setVisibility(View.INVISIBLE);
try {
Glide.with(getActivity()).load(students.get(position).getProimg()).into(holder.pro_img);
Glide.with(getActivity()).load(students.get(position).getBgimg()).into(holder.card_main);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return students.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView title, messages, invited, accepted, declined, eventTime;
private PorterShapeImageView pro_img;
ImageView card_main, status;
ViewPager viewPager;
LinearLayout sliderDots;
private ImageView[] dots;
private int dotsCount;
public ViewHolder(View itemView) {
super(itemView);
title = itemView.findViewById(R.id.xtv_welcome);
messages = itemView.findViewById(R.id.xtv_message);
invited = itemView.findViewById(R.id.xtv_invited);
accepted = itemView.findViewById(R.id.xtv_accepted);
declined = itemView.findViewById(R.id.xtv_decline);
eventTime = itemView.findViewById(R.id.contact_number);
pro_img = itemView.findViewById(R.id.pro_pic);
card_main = itemView.findViewById(R.id.card_main);
status = itemView.findViewById(R.id.incoming_image);
viewPager = itemView.findViewById(R.id.viewPagerTips);
sliderDots = itemView.findViewById(R.id.sliderDots);
dotsCount = pagerAdapter.getCount();
}
}
}
Please try to make one different array list for your viewpager's adapter:
ArrayList<Home_Model_ViewPager> tempList = new ArrayList<>();
for(int k=0;k<viewpagerData.size();k++){
Home_Model_ViewPager object = viewPagerData.get(k);
if(object.getTripDesc()!=null && object.getTripDesc().length() >0){
tempList.add(object);
}
}
ViewPagerAdapter pagerAdapter = new ViewPagerAdapter(getActivity(), tempList);
home_recycler.setAdapter(adapter);
adapter.notifyDataSetChanged();

Update the RecyclerView adapter items in fragment

I put a Recycler View into my fragment activity , which contains a number of Card View items
But when I click on the Refresh button, those items are created just for the first time
And when the Fragment is loaded for the next time, the items are not fetch again, and this is done only for the first time.
public class posts_fragment extends Fragment {
private List<PostData> PostDataList = new ArrayList<>();
PostDataAdapter adapter=new PostDataAdapter(PostDataList);
RecyclerView recyclerView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.posts_menu,container,false);
recyclerView =view.findViewById(R.id.PostRecycleView);
filldate();
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
public void filldate() {
//Start Get And Set Json Into Card View
final String KeyUrl="http://www.rasamdev.ir/salehin/GetPost.php";
final String KeyUsername="Key";
StringRequest stringRequest = new StringRequest(Request.Method.POST, KeyUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(getContext(),response, Toast.LENGTH_SHORT).show();
//Start Pars
if (response != null) {
try {
JSONObject jObject = new JSONObject(response);
JSONArray array = jObject.getJSONArray("Posts");
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
String puid = object.getString("puid");
String Ptitr = object.getString("Ptitr");
String ptext = object.getString("ptext");
String pdate = object.getString("pdate");
String plike = object.getString("plike");
String pview = object.getString("pview");
String pimg = object.getString("pimg");
PostDataList.add(new PostData(pdate,ptext,puid,Ptitr,pimg,pview,plike));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
//End Pars
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), error + "", Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() {
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put(KeyUsername,"13581358r#R");
return hashMap;
}
};
RequestQueue requestQueue= Volley.newRequestQueue(this.getActivity());
requestQueue.add(stringRequest);
//End
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onResume() {
adapter.notifyDataSetChanged();
super.onResume();
}
Adapter Class :
public class PostDataAdapter extends RecyclerView.Adapter<PostDataAdapter.MyViewHolder> {
private List<PostData> PostDataList ;
public static class MyViewHolder extends RecyclerView.ViewHolder {
public TextView vPostContent, vPostDate, vPostAuthor, vPostTitr,VPostLikes,VPostViews;
public ImageView vPostPhoto;
public MyViewHolder(View v) {
super(v);
vPostContent = v.findViewById(R.id.PostContentTv);
vPostDate = v.findViewById(R.id.PostDateTv);
vPostAuthor = v.findViewById(R.id.PostAuthorTv);
vPostTitr = v.findViewById(R.id.PostTitrTv);
vPostPhoto = v.findViewById(R.id.PostPhoto);
VPostLikes=v.findViewById(R.id.PostLikeTv);
VPostViews=v.findViewById(R.id.PostViewTv);
}
}
public PostDataAdapter(List<PostData> postDataList) {
PostDataList = postDataList;
}
#Override
public PostDataAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_posts, parent, false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.vPostDate.setText(PostDataList.get(position).getPostDate());
holder.vPostTitr.setText(PostDataList.get(position).getPostTitr());
holder.vPostContent.setText(PostDataList.get(position).getPostContent());
holder.vPostAuthor.setText(PostDataList.get(position).getPostAuthor());
holder.VPostViews.setText(PostDataList.get(position).getPostViews());
holder.VPostLikes.setText(PostDataList.get(position).getPostLikes());
new DownloadImageTask(holder.vPostPhoto).execute(PostDataList.get(position).getImgpost());
}
#Override
public int getItemCount() {
return PostDataList.size();
}
}
Data Class :
public class PostData {
private String PostDate, PostContent, PostAuthor, PostTitr, imgpost, PostViews, PostLikes;
public PostData(String postDate, String postContent, String postAuthor, String postTitr, String imgpost, String postViews, String postLikes) {
PostDate = postDate;
PostContent = postContent;
PostAuthor = postAuthor;
PostTitr = postTitr;
this.imgpost = imgpost;
PostViews = postViews;
PostLikes = postLikes;
}
public String getPostDate() {
return PostDate;
}
public void setPostDate(String postDate) {
PostDate = postDate;
}
public String getPostContent() {
return PostContent;
}
public void setPostContent(String postContent) {
PostContent = postContent;
}
public String getPostAuthor() {
return PostAuthor;
}
public void setPostAuthor(String postAuthor) {
PostAuthor = postAuthor;
}
public String getPostTitr() {
return PostTitr;
}
public void setPostTitr(String postTitr) {
PostTitr = postTitr;
}
public String getImgpost() {
return imgpost;
}
public void setImgpost(String imgpost) {
this.imgpost = imgpost;
}
public String getPostViews() {
return PostViews;
}
public void setPostViews(String postViews) {
PostViews = postViews;
}
public String getPostLikes() {
return PostLikes;
}
public void setPostLikes(String postLikes) {
PostLikes = postLikes;
}
}

search is not Working in section RecyclerView

i am trying implement search function in my section recyclerview
its not working but also not showing error...
i try with edittext addTextChangedListener method.
then in adapter add notifydatachanged method.
try with normal recyclerview its working fine but when use with section recyclerview its not working
sorry for bad english
here is mainActivty
here i get data from server and pass to the adapter in this class i am add the method for filter recyclerview
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_section_rv_search_prac);
init();
initView();
setUpRecyclerView();
tempModels = new ArrayList<TempModel>();
serviceRequest();
searchItem();
}
private void init() {
mAdapter = new ItemRecyclerViewAdapter(SectionRvSearchPrac.this);
}
private void initView() {
mEt_search = findViewById(R.id.et_search_main);
}
///////////////////////////////
private void searchItem() {
mEt_search.addTextChangedListener(
new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
#Override
public void afterTextChanged(Editable s) {
filter(s.toString());
}
});
}
//method for filter list is here..
private void filter(String text) {
ArrayList<TempModel> mFilter_list = new ArrayList<>();
for (TempModel tempModel : tempModels) {
if (tempModel.getName().toLowerCase().contains(text.toLowerCase())) {
mFilter_list.add(tempModel);
}
}
Log.d(TAG, "filter: " + mFilter_list);
mAdapter.filterList(mFilter_list);
}
//////////////////
private void setUpRecyclerView() {
recyclerView = (RecyclerView) findViewById(R.id.sectioned_recycler_view);
recyclerView.setHasFixedSize(true);
linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
}
private void serviceRequest() {
StringRequest stringRequest =
new StringRequest(
Request.Method.GET,
JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
parseJason(response);
}
},
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();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public void parseJason(String response) {
{
Log.d(TAG, "onResponse: " + response);
String[] first;
ArrayList<String> sewction_list = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("data");
String data = jsonArray.getString(0);
first = data.split(Pattern.quote("***^^^***"));
myList_sec = new ArrayList<>(Arrays.asList(first));
for (int j = 0; j < myList_sec.size(); j++) {
myList_first =
new ArrayList<>(Arrays.asList(myList_sec.get(j).split(Pattern.quote("^^^^"))));
sewction_list.add(myList_first.get(0));
myList_second =
new ArrayList<>(Arrays.asList(myList_first.get(1).split(Pattern.quote("^^"))));
ArrayList<String> id = new ArrayList<>();
ArrayList<String> url = new ArrayList<>();
ArrayList<String> img = new ArrayList<>();
ArrayList<String> name = new ArrayList<>();
for (int i = 0; i < myList_second.size(); i++) {
myList_third =
new ArrayList<>(Arrays.asList(myList_second.get(i).split(Pattern.quote("**"))));
url.add(myList_third.get(0));
img.add(myList_third.get(1));
name.add(myList_third.get(2));
id.add(myList_third.get(3));
tempModels.add(
new TempModel(
myList_third.get(2),
myList_third.get(0),
myList_third.get(1),
myList_third.get(3)));
}
sectionModelArrayList.add(new SectionModel(sewction_list, tempModels));
SectionRecyclerViewAdapter adapter =
new SectionRecyclerViewAdapter(
SectionRvSearchPrac.this, recyclerViewType, sectionModelArrayList);
recyclerView.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
here is myitemadapter class for child item
public class ItemRecyclerViewAdapter
extends RecyclerView.Adapter<ItemRecyclerViewAdapter.ItemViewHolder> {
private static final String TAG = "adapter";
private Context context;
ArrayList<TempModel> tempModels;
public ItemRecyclerViewAdapter(Context context) {
this.context = context;
}
public void setData(ArrayList<TempModel> data) {
this.tempModels = data;
}
#Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view =
LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_custom_row_layout, parent, false);
return new ItemViewHolder(view);
}
#Override
public void onBindViewHolder(ItemViewHolder holder, final int position) {
String path = tempModels.get(position).getImage();
holder.itemLabel.setText(tempModels.get(position).getName());
Picasso.get().load(path).into(holder.imageView);
holder.cardView.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {}
});
}
#Override
public int getItemCount() {
return tempModels.size();
}
/// here method for update filter list
public void filterList(ArrayList<TempModel> filterdNames) {
this.tempModels = filterdNames;
notifyDataSetChanged();
}
class ItemViewHolder extends RecyclerView.ViewHolder {
private TextView itemLabel;
ImageView imageView;
CardView cardView;
public ItemViewHolder(View itemView) {
super(itemView);
itemLabel = (TextView) itemView.findViewById(R.id.item_label);
cardView = itemView.findViewById(R.id.cardview);
imageView = itemView.findViewById(R.id.img);
}
}
section model for section item
public class SectionModel {
private ArrayList<String> sectionLabel;
private ArrayList<TempModel> tempModels;
public SectionModel(ArrayList<String> sectionLabel, ArrayList<TempModel> tempModels) {
this.sectionLabel = sectionLabel;
this.tempModels = tempModels;
}
public ArrayList<String> getSectionLabel() {
return sectionLabel;
}
public ArrayList<TempModel> getTempModels() {
return tempModels;
}
}
model class for item
public class TempModel implements Parcelable{
String name;
String url;
String image;
String num;
public TempModel() {
}
public TempModel(String name, String url, String image, String num) {
this.name = name;
this.url = url;
this.image = image;
this.num = num;
}
protected TempModel(Parcel in) {
name = in.readString();
url = in.readString();
image = in.readString();
num = in.readString();
}
public static final Creator<TempModel> CREATOR = new Creator<TempModel>() {
#Override
public TempModel createFromParcel(Parcel in) {
return new TempModel(in);
}
#Override
public TempModel[] newArray(int size) {
return new TempModel[size];
}
};
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(url);
dest.writeString(image);
dest.writeString(num);
}
}
sectionadapter class
public class SectionRecyclerViewAdapter
extends RecyclerView.Adapter<SectionRecyclerViewAdapter.SectionViewHolder> {
private static final String TAG = "section";
class SectionViewHolder extends RecyclerView.ViewHolder {
private TextView sectionLabel, showAllButton;
private RecyclerView itemRecyclerView;
public SectionViewHolder(View itemView) {
super(itemView);
sectionLabel = (TextView) itemView.findViewById(R.id.section_label);
itemRecyclerView = (RecyclerView) itemView.findViewById(R.id.item_recycler_view);
}
}
private Context context;
private RecyclerViewType recyclerViewType;
private ArrayList<SectionModel> sectionModelArrayList;
public SectionRecyclerViewAdapter(
Context context,
RecyclerViewType recyclerViewType,
ArrayList<SectionModel> sectionModelArrayList) {
this.context = context;
this.recyclerViewType = recyclerViewType;
this.sectionModelArrayList = sectionModelArrayList;
}
#Override
public SectionViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rrow, parent, false);
return new SectionViewHolder(view);
}
#Override
public void onBindViewHolder(SectionViewHolder holder, int position) {
final SectionModel sectionModel = sectionModelArrayList.get(position);
holder.sectionLabel.setText(sectionModel.getSectionLabel().get(position));
// recycler view for items
holder.itemRecyclerView.setHasFixedSize(true);
holder.itemRecyclerView.setNestedScrollingEnabled(false);
GridLayoutManager gridLayoutManager = new GridLayoutManager(context, 3);
holder.itemRecyclerView.setLayoutManager(gridLayoutManager);
/* set layout manager on basis of recyclerview enum type */
ItemRecyclerViewAdapter adapter = new ItemRecyclerViewAdapter(context);
adapter.setData(sectionModel.getTempModels());
holder.itemRecyclerView.setAdapter(adapter);
}
#Override
public int getItemCount() {
return sectionModelArrayList.size();
}
Your code very confusing so i just write my solution.
public class SomeAdapter extends RecyclerView.Adapter<SomeAdapter.SomeViewHolder> implements Filterable{
...
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
mMainList = mYourJSONResponseList;
FilterResults results = new FilterResults();
ArrayList<YourModel> mFilter_list = new ArrayList<>();
//Place your logic
for (YourModel model : mMainList) {
if(model.getName().
toLowerCase().contains(text.toLowerCase())) {
mFilter_list.add(model);
}
}
results.count = mFilter_list.size();
results.values = mFilter_list;
return results;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
mMainList = (ArrayList<YourModel>) filterResults.values;
notifyDataSetChanged();
}
};
return filter;
}
And add this into your text listener
#Override
public void afterTextChanged(Editable s) {
//Add this
adapter.getFilter().filter(s.toString())
}
NOTE!! You will show mMainList only this list in your RecyclerView, And check nullpointerexceptions

Remove JSON Object from JSON Array on onClick in Android

I have a RecyclerView and when a user clicks on an item, that item gets selected and its id is saved in a JSON Array. Similarly, if the user selects an item and later decides to unselect it, the item should be removed from the JSON Array and an updated array should be created. I am able to create a JSON Array on onClick but at !onClick I am not able to remove the JSON Object from the JSON Array.
Here is my Adapter Class:
public class ClientListAdapter extends RecyclerView.Adapter<ClientListAdapter.ViewHolder> {
private Context context;
private List<ClientListData> clientListData;
public JSONArray clientArray = new JSONArray();
public ClientListAdapter(List<ClientListData> clientListData, Context context) {
super();
this.clientListData = clientListData;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.client_list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final ClientListAdapter.ViewHolder holder, final int position) {
final ClientListData clientListDataModel = clientListData.get(position);
holder.clientList.setText(clientListDataModel.getClientName());
holder.itemView.setBackgroundColor(clientListDataModel.isSelected() ? Color.GRAY : Color.WHITE);
holder.clientList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clientListDataModel.setSelected(!clientListDataModel.isSelected());
try {
JSONObject clientObject = new JSONObject();
if(clientListDataModel.isSelected()) {
holder.itemView.setBackgroundColor(Color.GRAY);
clientObject.put("id", clientListData.get(position).getClientId());
clientArray.put(clientObject);
}
if(!clientListDataModel.isSelected()) {
holder.itemView.setBackgroundColor(Color.WHITE);
for(int i=0; i<clientArray.length(); i++) {
clientObject = clientArray.getJSONObject(i);
clientObject.remove(clientListData.get(position).getClientId());
//clientArray.put(clientObject);
}
}
//clientArray.put(clientObject);
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("client id array", ""+clientArray);
}
});
}
#Override
public int getItemCount() {
return clientListData == null ? 0:clientListData.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView clientList;
public ViewHolder(View itemView) {
super(itemView);
clientList = (TextView) itemView.findViewById(R.id.tv_client_list);
}
}
}
and here is my Model Class:
public class ClientListData {
private String clientId;
private String clientName;
private boolean isSelected = false;
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
}
Note that I have created a boolean variable in the Model Class to listen to onClicks.
Note:- since I am using org.json, I am not able to use the remove method on JSON Array, after a lot of search I came across this question.
Try this:[UPDATE]
if (!clientListDataModel.isSelected()) {
holder.itemView.setBackgroundColor(Color.WHITE);
for (int i = 0; i < clientArray.length(); i++) {
clientObject = clientArray.getJSONObject(i);
if (clientObject.getString("id").equals(clientListDataModel.getClientId())) {
clientArray=removeFromJsonArray(clientArray,i);
break;
}
}
}
removeFromJsonArray function:
private JSONArray removeFromJsonArray(JSONArray array,int position){
if(array==null)return null;
JSONArray newArray = new JSONArray();
for (int i=0;i<array.length();i++)
{
//Excluding the item at position
if (i != position)
{
newArray.put(jsonArray.get(i));
}
}
return newArray;
}
Add This code in activity
private ArrayList<Integer> selectedIdList = new ArrayList<>();
ClientListAdapter adapter=new ClientListAdapter (list,this,new View.OnClickListener() {
#Override
public void onClick(View v) {
int position=(Integer)v.getTag();
if(list.size()>position){
ClientListDataModel clientListDataModel=list.get(position);
if clientListDataModel!= null) {
clientListDataModel.setSelected(!clientListDataModel.isSelected());
boolean isSelected = clientListDataModel.isSelected();
if (!isSelected) {
if (selectedIdList.contains(clientListDataModel.getId())) {
int index = selectedIdList.indexOf(clientListDataModel.getId());
selectedIdList.remove(index);
}
} else {
if (!selectedIdList.contains(clientListDataModel.getId())) {
selectedIdList.add(clientListDataModel.getId());
}
}
}
adapter.notifyItemChanged(pos);
}
});
And at sending time
public JSONArray clientArray = new JSONArray();
if(!selectedIdList.empty()){
for(int i=0; i<selectedIdList.size(); i++) {
JSONObject clientObject = new JSONObject();
clientObject.put("id", selectedIdList.get(i));
clientArray.put(clientObject);
}
}
public class ClientListAdapter extends RecyclerView.Adapter<ClientListAdapter.ViewHolder> {
private Context context;
private List<ClientListData> clientListData;
public JSONArray clientArray = new JSONArray();
OnClickListener onClickListener;
public ClientListAdapter(List<ClientListData> clientListData, Context context,OnClickListener onclick) {
super();
this.clientListData = clientListData;
this.context = context;
onClickListener=onclick;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.client_list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final ClientListAdapter.ViewHolder holder, final int position) {
final ClientListData clientListDataModel = clientListData.get(position);
holder.clientList.setText(clientListDataModel.getClientName());
holder.itemView.setBackgroundColor(clientListDataModel.isSelected() ? Color.GRAY : Color.WHITE);
holder.clientList.setTag(position);
holder.clientList.setOnClickListener(onClickListener);
}
#Override
public int getItemCount() {
return clientListData == null ? 0:clientListData.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView clientList;
public ViewHolder(View itemView) {
super(itemView);
clientList = (TextView) itemView.findViewById(R.id.tv_client_list);
}
}

Recyclerview sort by time ascending

I have a recyclerview that display news.
News is composed by name_news,image_news,time_news.
I am getting the data from mysqldatabse.
This is my adapter class:
public class PostAdapter2 extends RecyclerView.Adapter<PostAdapter2.ViewHolder>{
public Context c;
public FragmentManager mContext;
public ArrayList<News_data> original_items = new ArrayList<>();
public ArrayList<News_data> filtered_items = new ArrayList<>();
public ArrayList<Simplenews_data> original_items2 = new ArrayList<>();
public ArrayList<Simplenews_data> filtered_items2 = new ArrayList<>();
// ItemFilter mFilters = new ItemFilter();
public PostAdapter2(Context c, ArrayList<News_data> postList) {
this.c = c;
this.original_items = postList;
this.filtered_items = postList;
}
public PostAdapter2(FragmentManager mContext, ArrayList<Simplenews_data> postList) {
this.mContext = mContext;
this.original_items2 = postList;
this.filtered_items2 = postList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_news, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
try {
final Simplenews_data post = filtered_items2.get(position);
PicassoClient.downloadImage(c, post.getImage_simplenews(), holder.image_news);
holder.txt_news_title.setText(post.getName_simplenews());
holder.txt_date.setText(post.getTime_simplenews());
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick() {
Bundle x = new Bundle();
x.putString("news_title", post.getName_simplenews());
x.putString("news", post.getDesc_simplenews());
x.putString("image",post.getImage_simplenews());
x.putString("time",post.getTime_simplenews());
x.putString("date",post.getDate_simplenews());
Fragment descriptionFragment = new DescriptionFragment();
FragmentTransaction transaction = mContext.beginTransaction();
descriptionFragment.setArguments(x);
transaction.replace(R.id.framelayout, descriptionFragment).addToBackStack(null).commit();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return filtered_items2.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ItemClickListener itemClickListener;
TextView txt_news_title,txt_date;
ImageView image_news;
public ViewHolder(View itemView) {
super(itemView);
txt_news_title = (TextView) itemView.findViewById(R.id.txt_news_title);
txt_date = (TextView) itemView.findViewById(R.id.txt_timedate);
image_news = (ImageView) itemView.findViewById(R.id.image_news);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
try {
this.itemClickListener.onItemClick();
}catch (Exception e)
{
e.printStackTrace();
}
}
public void setItemClickListener(ItemClickListener itemClickListener)
{
this.itemClickListener=itemClickListener;
}
}
}
I am using a PHP interface to add news.
The getTime_simplenews() contains the news sumbmitted time format as : 14:00
So i want to display the immediate news in Top of recyclerview not under the previous news.
Thanks a lot.
UPDATED :
public class Simplenews_data {
int id_simplenews;
String name_simplenews,image_simplenews,desc_simplenews,time_simplenews,date_simplenews;
public String getDate_simplenews() {
return date_simplenews;
}
public void setDate_simplenews(String date_simplenews) {
this.date_simplenews = date_simplenews;
}
public String getTime_simplenews() {
return time_simplenews;
}
public void setTime_simplenews(String time_simplenews) {
this.time_simplenews = time_simplenews;
}
public int getId_simplenews() {
return id_simplenews;
}
public void setId_simplenews(int id_simplenews) {
this.id_simplenews = id_simplenews;
}
public String getName_simplenews() {
return name_simplenews;
}
public void setName_simplenews(String name_simplenews) {
this.name_simplenews = name_simplenews;
}
public String getImage_simplenews() {
return image_simplenews;
}
public void setImage_simplenews(String image_simplenews) {
this.image_simplenews = image_simplenews;
}
public String getDesc_simplenews() {
return desc_simplenews;
}
public void setDesc_simplenews(String desc_simplenews) {
this.desc_simplenews = desc_simplenews;
}
Fragment Code:
public void parseJson2(String response) {
try {
JSONArray array = new JSONArray(response);
JSONObject jsonObject = null;
post_array2.clear();
Simplenews_data p;
for (int i = 0; i < array.length(); i++) {
jsonObject = array.getJSONObject(i);
int id_simplenews = jsonObject.getInt("id_simplenews");
String name_simplenews = jsonObject.getString("name_simplenews");
String image_simplenews = jsonObject.getString("image_simplenews");
String desc_simplenews = jsonObject.getString("desc_simplenews");
String time_simplenews = jsonObject.getString("time_simplenews");
String date_simplenews = jsonObject.getString("date_simplenews");
p = new Simplenews_data();
p.setId_simplenews(id_simplenews);
p.setName_simplenews(name_simplenews);
p.setImage_simplenews(image_simplenews);
p.setDesc_simplenews(desc_simplenews);
p.setTime_simplenews(time_simplenews);
p.setDate_simplenews(date_simplenews);
post_array2.add(p);
}
} catch (JSONException e) {
swipeRefreshLayout.setRefreshing(false);
e.printStackTrace();
}
adapter = new PostAdapter2(getFragmentManager(), post_array2);
recycler_post.setAdapter(adapter);
swipeRefreshLayout.setRefreshing(false);
}
I have updated your model class and implemented Comparable to it
public class Simplenews_data implements Comparable<Simplenews_data> {
int id_simplenews;
String name_simplenews,image_simplenews,desc_simplenews,time_simplenews,date_simplenews;
public String getDate_simplenews() {
return date_simplenews;
}
public void setDate_simplenews(String date_simplenews) {
this.date_simplenews = date_simplenews;
}
public String getTime_simplenews() {
return time_simplenews;
}
public void setTime_simplenews(String time_simplenews) {
this.time_simplenews = time_simplenews;
}
public int getId_simplenews() {
return id_simplenews;
}
public void setId_simplenews(int id_simplenews) {
this.id_simplenews = id_simplenews;
}
public String getName_simplenews() {
return name_simplenews;
}
public void setName_simplenews(String name_simplenews) {
this.name_simplenews = name_simplenews;
}
public String getImage_simplenews() {
return image_simplenews;
}
public void setImage_simplenews(String image_simplenews) {
this.image_simplenews = image_simplenews;
}
public String getDesc_simplenews() {
return desc_simplenews;
}
public void setDesc_simplenews(String desc_simplenews) {
this.desc_simplenews = desc_simplenews;
}
#Override
public int compareTo(MyObject o) {
Date newDate = formatDateTime(o.getTime_simplenews(), "HH:mm", "YYYY-MM-DD HH:mm");
Date inputDate = formatDateTime(getTime_simplenews(), "HH:mm", "YYYY-MM-DD HH:mm");
return inputDate.compareTo(newDate);
}
public Date formatDateTime(String date, String fromFormat, String toFormat) {
Date d = null;
try {
d = new SimpleDateFormat(fromFormat, Locale.US).parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return new SimpleDateFormat(toFormat, Locale.US).parse(d);
}
}
Sort the list using below code
Collections.sort(yourList);

Categories

Resources