Spinner In Custom ListView Randomly Changed When Scrolling - java

I Just need to fix the value inside Spinner when i select some value and SetEnabled True/False when i checked the CheckBox.
For example when i check the chekcbox, the spinner will be enabled and do the opposite when i uncheck the checkbox.
However it will changing randomly when i just scrolling.
This my code :
CustomListView.java
class CustomListView extends BaseAdapter {
private ArrayList<ListItem2> listData;
private LayoutInflater layoutInflater;
private Context context;
public CustomListView adapter = this;
String jmlCmbSiap;
ArrayList<String> a = new ArrayList<>();
public CustomListView(Context context, ArrayList<ListItem2> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
this.context = context;
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
newsItem = listData.get(position);
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.listview_detail_order, null);
holder = new ViewHolder();
newsItem.setAdapter(Integer.parseInt(newsItem.getJumlah()));
holder.txtBarang = (TextView) convertView.findViewById(R.id.txtBarang);
holder.txtJumlah = (TextView) convertView.findViewById(R.id.txtJumlah);
holder.txtBox = (TextView) convertView.findViewById(R.id.txtBoxes);
holder.cmbSiap = (Spinner) convertView.findViewById(R.id.cmbSiap);
holder.cmbSiap.setAdapter(newsItem.getAdapter());
holder.thumbImage = (ImageView) convertView.findViewById(R.id.thumbImage);
holder.chkOk = (CheckBox) convertView.findViewById(R.id.chkOk);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Picasso
.with(context)
.load(newsItem.getImg())
.placeholder(R.drawable.placeholder)
.error(R.drawable.placeholder)
.into(holder.thumbImage);
holder.txtBarang.setText(newsItem.getNamaProduk().toUpperCase());
holder.txtJumlah.setText(newsItem.getJumlah().toUpperCase());
holder.cmbSiap.setSelection(Integer.parseInt(newsItem.getJumlah()));
holder.cmbSiap.setEnabled(newsItem.getcmbSiap());
holder.txtBox.setEnabled(newsItem.gettxtBox());
holder.cmbSiap.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
jmlCmbSiap = parent.getItemAtPosition(position).toString();
newsItem.setJumlah(jmlCmbSiap);
holder.cmbSiap.setSelection(Integer.parseInt(newsItem.getJumlah()));
System.out.println("JML : " + newsItem.getJumlah());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
holder.chkOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (newsItem.getchkOk() == false) {
newsItem.setcmbSiap(true);
newsItem.setchkOk(true);
newsItem.settxtBox(true);
holder.cmbSiap.setEnabled(true);
holder.chkOk.setChecked(true);
txtBox.setEnabled(true);
numberChecked = numberChecked + 1;
idChkOk.add(position);
System.out.println("Chk : " + idChkOk);
} else {
numberChecked = numberChecked - 1;
newsItem.setcmbSiap(false);
newsItem.setchkOk(false);
holder.cmbSiap.setEnabled(false);
holder.chkOk.setChecked(false);
if (numberChecked == 0) {
newsItem.settxtBox(false);
txtBox.setEnabled(false);
}
idChkOk.remove(position);
System.out.println("Chk : " + idChkOk);
}
}
});
cmdPak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
a.clear();
for (int i = 0; i < listData.size(); i++)
{
newsItem = listData.get(i);
a.add(newsItem.getJumlah().toString());
}
System.out.println("Pak : " + a);
}
});
return convertView;
}
class ViewHolder {
TextView txtBarang,txtJumlah,txtBox;
Spinner cmbSiap;
ImageView thumbImage;
CheckBox chkOk;
}
}
ListItem2.java
class ListItem2 {
private String shipment;
private String truck;
private String transporter;
private String tanggal;
private String order;
private String nilai;
private String alamat;
private String status;
private String jumlah;
private String namaProduk;
private String img;
private String sopir;
private String jumlahTerima;
private String alasan;
private String orderTemp;
private Boolean chkOk;
private Boolean cmbSiap;
private Boolean txtBox;
private ArrayAdapter<CharSequence> adapter;
private ArrayList<String> array = new ArrayList<String>();
public void setAdapter(Integer jml)
{
for (int i = 0; i<= jml; i++) {
array.add(String.valueOf(i));
}
adapter = new ArrayAdapter(DetailOrder.this,android.R.layout.simple_spinner_item,array);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}
public ArrayAdapter<CharSequence> getAdapter()
{
return adapter;
}
public void setTanggal(String tanggal) {
this.tanggal = tanggal;
}
public String getOrder() {
return order;
}
public void setOrder(String order) {
this.order = order;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getAlamat() {
return alamat;
}
public void setAlamat(String alamat) {
this.alamat = alamat;
}
public String getNilai() {
return nilai;
}
public void setNilai(String nilai) {
this.nilai = nilai;
}
public String getKodeProduk() {
return nilai;
}
public void setKodeProduk(String nilai) {
this.nilai = nilai;
}
public String getNamaProduk() {
return namaProduk;
}
public void setNamaProduk(String namaProduk) {
this.namaProduk = namaProduk;
}
public String getJumlah() {
return jumlah;
}
public void setJumlah(String jumlah) {
this.jumlah = jumlah;
}
public Boolean getchkOk() {
return chkOk;
}
public void setchkOk(Boolean chkOk) {
this.chkOk = chkOk;
}
public Boolean getcmbSiap() {
return cmbSiap;
}
public void setcmbSiap(Boolean cmbSiap) {
this.cmbSiap = cmbSiap;
}
public Boolean gettxtBox() {
return txtBox;
}
public void settxtBox(Boolean txtBox) {
this.txtBox = txtBox;
}
}
Could you lend me a hand ?
Update :
chkAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View views;
CheckBox chkOkx;
Spinner cmbSiap;
for (int i = 0; i < jArray; i++) {
final ListItem2 newsItem = listData.get(i);
views = listView.getChildAt(i);
if (views == null) {
return;
} else {
chkOkx = (CheckBox) views.findViewById(R.id.chkOk);
cmbSiap = (Spinner) views.findViewById(R.id.cmbSiap);
if (chkOkx.isChecked()) {
newsItem.setchkOk(true);
newsItem.setcmbSiap(true);
chkOkx.setChecked(newsItem.getchkOk());
cmbSiap.setEnabled(newsItem.getcmbSiap());
} else {
newsItem.setchkOk(false);
newsItem.setcmbSiap(false);
chkOkx.setChecked(newsItem.getchkOk());
cmbSiap.setEnabled(newsItem.getcmbSiap());
}
idChkOk.add(i);
}
}
if (chkAll.isChecked()) {
txtBox.setEnabled(true);
numberChecked = 0;
} else {
txtBox.setEnabled(false);
numberChecked = listviewChild;
}
listView.invalidateViews();
}
});

In ListView when you scroll, the views are destroyed and re-created. To overcome the issue you need to preserve both of the checkbox status and spinner item's value.
For the checkbox, save the checked status from setOnClickListener inside a boolean array,
if (((CheckBox) v).isChecked()) {
checkBoxState[position] = true;
} else {
checkBoxState[position] = false;
}
The boolean array should like this,
private boolean[] checkBoxState;
Later on getView() apply the check/uncheck status of each checkbox items based on the array
holder.checkBox.setChecked(checkBoxState[position]);
Similarly to save the spinner data, create a Hashmap
Map<Integer, Integer> myMap = new HashMap<Integer, Integer>();
and save the spinner data once it's selected from the setOnItemSelectedListener
myMap.put(position, pos);
Later restore the spinner selection position from the saved data,
if (myMap.containsKey(position)) {
viewHolder.spinner.setSelection(myMap.get(position));
}
Full code,
class CustomListView extends BaseAdapter {
private ArrayList<ListItem2> listData;
private LayoutInflater layoutInflater;
private Context context;
public CustomListView adapter = this;
String jmlCmbSiap;
ArrayList<String> a = new ArrayList<>();
private boolean[] checkBoxState;
private Map<Integer, Integer> myMap = new HashMap<Integer, Integer>();
public CustomListView(Context context, ArrayList<ListItem2> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
checkBoxState = new boolean[listData.size()];
this.context = context;
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
newsItem = listData.get(position);
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.listview_detail_order, null);
holder = new ViewHolder();
newsItem.setAdapter(Integer.parseInt(newsItem.getJumlah()));
holder.txtBarang = (TextView) convertView.findViewById(R.id.txtBarang);
holder.txtJumlah = (TextView) convertView.findViewById(R.id.txtJumlah);
holder.txtBox = (TextView) convertView.findViewById(R.id.txtBoxes);
holder.cmbSiap = (Spinner) convertView.findViewById(R.id.cmbSiap);
holder.cmbSiap.setAdapter(newsItem.getAdapter());
holder.thumbImage = (ImageView) convertView.findViewById(R.id.thumbImage);
holder.chkOk = (CheckBox) convertView.findViewById(R.id.chkOk);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.checkBox.setChecked(checkBoxState[position]);
if (checkBoxState[position])
{
holder.chkOk.setChecked(true);
newsItem.setcmbSiap(true);
newsItem.settxtBox(true);
holder.cmbSiap.setEnabled(true);
holder.cmbSiap.setClickable(true);
txtBox.setEnabled(true);
}
else
{
holder.chkOk.setChecked(false);
newsItem.setcmbSiap(false);
newsItem.settxtBox(false);
holder.cmbSiap.setEnabled(false);
holder.cmbSiap.setClickable(false);
txtBox.setEnabled(false);
}
Picasso
.with(context)
.load(newsItem.getImg())
.placeholder(R.drawable.placeholder)
.error(R.drawable.placeholder)
.into(holder.thumbImage);
holder.txtBarang.setText(newsItem.getNamaProduk().toUpperCase());
holder.txtJumlah.setText(newsItem.getJumlah().toUpperCase());
holder.cmbSiap.setSelection(Integer.parseInt(newsItem.getJumlah()));
holder.cmbSiap.setEnabled(newsItem.getcmbSiap());
holder.txtBox.setEnabled(newsItem.gettxtBox());
if (myMap.containsKey(position)) {
viewHolder.spinner.setSelection(myMap.get(position));
}
holder.cmbSiap.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
jmlCmbSiap = parent.getItemAtPosition(position).toString();
newsItem.setJumlah(jmlCmbSiap);
myMap.put(position, pos);
System.out.println("JML : " + newsItem.getJumlah());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
holder.chkOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//is chkOk checked?
if (((CheckBox) v).isChecked()) {
checkBoxState[position] = true;
viewHolder.spinner.setEnabled(true);
viewHolder.spinner.setClickable(true);
} else {
checkBoxState[position] = false;
viewHolder.spinner.setEnabled(false);
viewHolder.spinner.setClickable(false);
}
}
});
cmdPak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
a.clear();
for (int i = 0; i < listData.size(); i++)
{
newsItem = listData.get(i);
a.add(newsItem.getJumlah().toString());
}
System.out.println("Pak : " + a);
}
});
return convertView;
}
class ViewHolder {
TextView txtBarang,txtJumlah,txtBox;
Spinner cmbSiap;
ImageView thumbImage;
CheckBox chkOk;
}
}
Update:
In order to make a select all/deselect all checkbox feature,
create a boolean flag at the top of adapter's class,
boolean isCheckAll = false;
then create a toggle method,
public void toggleCheckAll() {
isCheckAll = !isCheckAll;
for (int i = 0; i < listData.size(); i++) {
if (isCheckAll) {
checkBoxState[i] = true;
notifyDataSetInvalidated();
} else {
checkBoxState[i] = false;
notifyDataSetInvalidated();
}
}
}
Now call the method from your aactivity's check all button's click,
btnCheckAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
adapter.toggleCheckAll();
}
});

Related

Adapter of RecyclerView doesn't update data after changing the array

I have an abstract class "ListItem" with two subclasses - "Header"(Data) and "Event". Depending on the situation, the array should be displayed either as "Header" - "Events of this data", or just events.
The created object of the "Event" class is passed to the main fragment from a separate activity. If I only need to display events, I just write it to an array and update the adapter data, it works. If, after creating a class object, I need to display it and existing events in the form "Header" - "Events", then the adapter for some reason is not updated and the new event is not displayed. If you close the application and reopen it, the event appears in its normal form with a header.
Here's my RV Adapter
public class EventAdapter extends RecyclerView.Adapter<EventAdapter.EventViewHolder> {
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
private static final String TAG = "myLogs";
private ArrayList<ListItem> list;
final SparseBooleanArray selectedItems = new SparseBooleanArray();
private int currentSelectedPos;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMMM", myDateFormatSymbols);
public EventAdapter(ArrayList<ListItem> items){
list = items;
}
public ArrayList<ListItem> getItems(){
return list;
}
private EventAdapterListener itemClickListener;
public interface EventAdapterListener {
void onItemClick(int position);
void onItemLongClick(int position);
}
public void setListener(EventAdapterListener listener){
itemClickListener = listener;
}
private OnItemCheckedListener OnItemChecked;
public interface OnItemCheckedListener {
void onItemChecked(int position, boolean isImportant);
}
public void setOnItemCheckedListener (OnItemCheckedListener listener){
OnItemChecked = listener;
}
public static class EventViewHolder extends RecyclerView.ViewHolder{
public TextView TVtitle;
public TextView TVcomment;
public CheckBox CBimportance;
public TextView TVdate;
//public EventViewHolder(#NonNull View itemView, final EventAdapterListener listener) {
public EventViewHolder(#NonNull View itemView) {
super(itemView);
}
}
public void removeAllObjectsOf(Class<? extends ListItem> cls) {
Iterator itr = list.iterator();
while (itr.hasNext()) {
if (itr.next().getClass().equals(cls)) {
itr.remove();
}
}
notifyDataSetChanged();
}
Comparator<ListItem> dateComparator = new Comparator<ListItem>() {
#Override
public int compare(ListItem event, ListItem t1) {
return ((Event)(event)).Date.compareTo(((Event)t1).Date);
}
};
Comparator<ListItem> importanceComparator = new Comparator<ListItem>() {
#Override
public int compare(ListItem event, ListItem t1) {
return ((Event)(event)).IsImportant.compareTo(((Event)t1).IsImportant);
}
};
Comparator<ListItem> nameComparator = new Comparator<ListItem>() {
#Override
public int compare(ListItem event, ListItem t1) {
return ((Event)(event)).Name.compareTo(((Event)t1).Name);
}
};
Comparator<ListItem> completenessComparator = new Comparator<ListItem>() {
#Override
public int compare(ListItem event, ListItem t1) {
return ((Event)(event)).IsComplete.compareTo(((Event)t1).IsComplete);
}
};
public void sortBy(Comparator<ListItem> comparator, ArrayList<ListItem> list) {
removeAllObjectsOf(Header.class);
Collections.sort(list, comparator);
}
public void groupByDate()
{
ArrayList<ListItem> result = new ArrayList<>();
removeAllObjectsOf(Header.class);
sortBy(dateComparator, list);
ArrayList<Long> dates = new ArrayList<>();
for (ListItem event: list)
{
if (!(dates.contains(((Event)event).getDate())))
{
dates.add(((Event)event).getDate());
ArrayList<ListItem> ei = getItemsbyDate(list, ((Event)event).getDate());
Header header = new Header();
header.setHeader(String.valueOf(((Event)event).getDate()));
result.add(header);
result.addAll(ei);
}
}
list = result;
notifyDataSetChanged();
}
public ArrayList<ListItem> getItemsbyDate(ArrayList<ListItem> items, Long date){
ArrayList<ListItem> result = new ArrayList<>();
for (ListItem ci : items){
if (((Event)ci).getDate().equals(date)){
result.add(ci);
}
}
return result;
}
public void removeItem(int position) {
list.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position,list.size());
}
#Override
public int getItemViewType(int position) {
if (isPositionHeader(position))
return TYPE_HEADER;
return TYPE_ITEM;
}
private boolean isPositionHeader(int position) {
return list.get(position) instanceof Header;
}
private static DateFormatSymbols myDateFormatSymbols = new DateFormatSymbols(){
#Override
public String[] getMonths() {
return new String[]{"января", "февраля", "марта", "апреля", "мая", "июня",
"июля", "августа", "сентября", "октября", "ноября", "декабря"};
}
};
#NonNull
#Override
public EventViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
if (viewType == TYPE_HEADER){
View v = inflater.inflate(R.layout.group_layout, parent, false);
return new VHHeader(v);
} else {
View v = inflater.inflate(R.layout.list_item_cardview, parent, false);
return new VHItem(v);
}
}
#Override
public void onBindViewHolder(#NonNull EventViewHolder holder, final int position)
{
if (holder instanceof VHHeader){
Header currentItem = (Header) list.get(position);
VHHeader VHheader = (VHHeader) holder;
VHheader.txtTitle.setText(simpleDateFormat.format(Long.parseLong(currentItem.getHeader())));
} else if (holder instanceof VHItem) {
final Event event = (Event) list.get(position);
VHItem VHitem = (VHItem) holder;
VHitem.txtName.setText(event.getName());
VHitem.txtDate.setText(simpleDateFormat.format(event.getDate()));
VHitem.TVcomment.setText(event.getComment());
VHitem.CBimportance.setOnCheckedChangeListener(null);
VHitem.CBimportance.setChecked(event.getImportant());
VHitem.CBimportance.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
event.IsImportant = b;
OnItemChecked.onItemChecked(position, b);
}
});
VHitem.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (selectedItems.size() > 0 && itemClickListener != null){
itemClickListener.onItemClick(position);
}
}
});
VHitem.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
if (itemClickListener != null){
itemClickListener.onItemLongClick(position);
}
return true;
}
});
if (currentSelectedPos == position) currentSelectedPos = -1;
}
}
#Override
public int getItemCount() {
return (list == null) ? 0 : list.size();
}
void deleteEvents(){
List<ListItem> selectedEvents = new ArrayList<>();
for (ListItem item : list){
if (item instanceof Event){
if (((Event) item).getSelected()){
selectedEvents.add(item);
}
}
}
list.removeAll(selectedEvents);
//notifyDataSetChanged();
currentSelectedPos = -1;
deleteEmptyHeaders();
}
public int getCountofHeaderItems(Header header)
{
int k = 0;
for (ListItem item: list)
{
if (item instanceof Event){
if (((Event) item).Date.equals(Long.parseLong(header.getHeader()))){
k++;
}
}
}
return k;
}
void deleteEmptyHeaders(){
List<Header> headers = new ArrayList<>();
for (ListItem event : list){
if (event instanceof Header){
if (getCountofHeaderItems((Header)event) == 0){
headers.add((Header)event);
}
}
}
list.removeAll(headers);
}
void toggleSelection(int position) {
if (getItemViewType(position) == TYPE_ITEM){
currentSelectedPos = position;
if (selectedItems.get(position)) {
selectedItems.delete(position);
((Event)list.get(position)).setSelected(false);
} else {
selectedItems.put(position, true);
((Event)list.get(position)).setSelected(true);
}
notifyItemChanged(position);
}
}
class VHHeader extends EventAdapter.EventViewHolder {
TextView txtTitle;
public VHHeader(View itemView) {
super(itemView);
this.txtTitle = (TextView) itemView.findViewById(R.id.tvTitleGroup);
}
}
class VHItem extends EventAdapter.EventViewHolder {
TextView txtName;
TextView txtDate;
TextView TVcomment;
CheckBox CBimportance;
public VHItem(View itemView) {
super(itemView);
this.txtName = (TextView) itemView.findViewById(R.id.tvTitle);
this.txtDate = (TextView) itemView.findViewById(R.id.tvDate);
this.TVcomment = (TextView) itemView.findViewById(R.id.tvComment);
this.CBimportance = (CheckBox) itemView.findViewById(R.id.cbIconImportant);
}
}
}
Here's my MainFragment:
private final static String ONLY_EVENTS = "ONLY_EVENTS";
private final static String GROUP_EVENTS_BY_DATE = "GROUP_EVENTS_BY_DATE";
ArrayList<ListItem> events;
private String ShowMode = ONLY_EVENTS;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_first_new, container, false);
events = read(this.getActivity(), PROCESSED_EVENTS);
if (events == null)
events = new ArrayList<ListItem>();
rvEvent = view.findViewById(R.id.recyclerview);
rvEvent.setHasFixedSize(true);
lmEvent = new LinearLayoutManager(this.getContext());
adapterEvent = new EventAdapter(events);
rvEvent.setLayoutManager(lmEvent);
rvEvent.setAdapter(adapterEvent);
ShowEvents(ShowMode);
initSwipe();
return view;
}
public void ShowEvents(String mode){
switch (mode){
case ONLY_EVENTS:
adapterEvent.removeAllObjectsOf(Header.class);
break;
case GROUP_EVENTS_BY_DATE:
adapterEvent.groupByDate();
break;
}
}
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && requestCode == 1) {
Event nd = (Event) data.getSerializableExtra("class");
events.add(nd);
write(this.getActivity(), events, PROCESSED_EVENTS);
if (ShowMode.equals(GROUP_EVENTS_BY_DATE))
adapterEvent.groupByDate();
adapterEvent.notifyDataSetChanged();
}
}
public static void write(Context context, ArrayList<ListItem> events, String Key) {
Gson gson = new Gson();
String jsonString = gson.toJson(events);
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = pref.edit();
editor.putString(Key, jsonString);
editor.apply();
}
public static ArrayList<ListItem> read(Context context, String Key) {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
String jsonString = pref.getString(Key, "");
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<Event>>() {
}.getType();
ArrayList<ListItem> list = gson.fromJson(jsonString, type);
return list;
}
This is how the Event is sent from the activity:
Intent intent = new Intent(NewEvent.this, FirstFragment.class);
//intent.putExtra("name", (String) etName.getText().toString());
objectEvent = new Event(etName.getText().toString(), date, etComment.getText().toString(), etType.getText().toString(), etNotif.getText().toString(), swIsComplete.isChecked(), false);
intent.putExtra("class", objectEvent);
setResult(RESULT_OK, intent);
finish();
UPD. In OnActivityResult after executing the line adapterEvent.groupByDate(); nothing changes. Changes take place in the array list in the adapter, but for some reason they do not go into the array that is used in the fragment. In the ShowEvents procedure, the same line of code works, and after it the array is changed.

How to change one adapter value from another adapter?

I have a little bit problem.In my activity there is two Adapter one is for color selection and another is for size selection. While i clicked one of the item of color then recently the available size adapter should be change but i got problem in size adapter. it changes only when i click the size item. I research and try to solve problem but it doesnt works for me.
Here is my code.
AddToCartActivity.java
public class AddToCartActivity extends BaseActivity{
#Override
protected int getLayout() {
return R.layout.activity_add_to_cart;
}
#Override
protected void init() {
//api called here
}
// response of api
#Override
public void productDetail(ProductCommonModel productCommonModel,
ArrayList<ProductChildModel> productChildModels, HashMap<Integer,
ArrayList<ChildAttributeModel>> childWithAttribute, HashMap<Integer,
ArrayList<ChildImageModel>> childWithImages,
ArrayList<com.hazesoft.dokan.singleproductdetail.model.ColorModel>
colorModels, ArrayList<SizeModel> sizeModels,
ArrayList<RelatedProductModel> relatedProductModels) {
this.productCommonModel = productCommonModel;
this.productChildModels = productChildModels;
this.childWithAttribute = childWithAttribute;
this.childWithImages = childWithImages;
this.colorModels = colorModels;
this.sizeModels = sizeModels;
this.relatedProductModels = relatedProductModels;
tvProductName.setText(productCommonModel.getName());
if (productCommonModel.getSpecialPrice() == 0) {
tvSellingPrice.setText(getString(R.string.rs) + productCommonModel.getSellingPrice());
tvDiscount.setVisibility(View.GONE);
tvSpecialPrice.setVisibility(View.GONE);
} else {
tvSpecialPrice.setText(getString(R.string.rs) + productCommonModel.getSpecialPrice());
tvSellingPrice.setText(getString(R.string.rs) + productCommonModel.getSellingPrice());
tvSellingPrice.setPaintFlags(tvSellingPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
tvDiscount.setText(productCommonModel.getDiscount() + getString(R.string.percentage));
}
setChildDetail(childWithAttribute, productChildModels);
setColorModel(colorModels);
setSizeModel(sizeModels);
quantity = Integer.parseInt(tvQuantityCart.getText().toString());
}
// setcolor adapter
private void setColorModel(ArrayList<ColorModel> colorModels) {
MyColorGridViewAdapter adapter = new MyColorGridViewAdapter(this, colorModels);
gvColor.setAdapter(adapter);
gvColor.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
adapter.setSelectedPostion(position);
adapter.notifyDataSetChanged();
}
});
}
// set size adapter
private void setSizeModel(ArrayList<SizeModel> sizeModels) {
sizeCustomModels = new ArrayList<>();
for(int i=0;i<sizeModels.size();i++){
sizeCustomModels.add(new SizeCustomModel(sizeModels.get(i).getAttName(),0));
}
setCustomSizeModelToAdapter(sizeCustomModels);
}
// this is code when i click color and change the size adapter but size doesnt change recently only changes when i click any item of the size
public void getSelectedC0lor(String color) {
selectedColor = color;
selectedSize=null;
sizeCustomModels = new ArrayList<>();
availableSize = new ArrayList<>();
for (int i = 0; i < skuColorSIzeList.size(); i++) {
if (skuColorSIzeList.get(i).getColor().equals(selectedColor)) {
availableSize.add(skuColorSIzeList.get(i).getSize());
}
}
for(int i=0;i<sizeModels.size();i++){
String size = null;
int status=0;
for(int j=0;j<availableSize.size();j++){
if(sizeModels.get(i).getAttName().equals(availableSize.get(j))){
size = sizeModels.get(i).getAttName();
status = 1;
break;
}else {
size = sizeModels.get(i).getAttName();
status = 0;
}
}
sizeCustomModels.add(new SizeCustomModel(size,status));
}
sizeRecylerAdapter.getNewModel(sizeCustomModels);
/*sizeRecylerAdapter = new MyCustomSizeRecylerAdapter(sizeCustomModels,this);
rvSize.setAdapter(sizeRecylerAdapter);
sizeRecylerAdapter.notifyDataSetChanged();*/
/*setCustomSizeModelToAdapter(sizeCustomModels);*/
}
}
MyColorGridViewAdapter.java
public class MyColorGridViewAdapter extends BaseAdapter {
Context context;
List<ColorModel> colorModelList;
String select_color;
boolean ch =false;
int checkPosition = -1;
public MyColorGridViewAdapter(Context context, List<ColorModel> colorModelList) {
this.context = context;
this.colorModelList = colorModelList;
}
public void setSelectedPostion(int postion){
this.checkPosition = postion;
}
#Override
public int getCount() {
return colorModelList.size();
}
#Override
public Object getItem(int position) {
return colorModelList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView==null){
convertView = LayoutInflater.from(context).inflate(R.layout.custom_color_list_item,null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
Picasso.with(context).load(colorModelList.get(position).getImage()).into(holder.ivImage);
holder.tvColorName.setText(colorModelList.get(position).getAttName());
if(checkPosition==position){
holder.ivChecked.setVisibility(View.VISIBLE);
select_color = colorModelList.get(position).getAttName();
if( context instanceof AddToCartActivity){
((AddToCartActivity) context).getSelectedC0lor(select_color);
}
}else {
holder.ivChecked.setVisibility(View.GONE);
}
if(colorModelList.size()==1){
holder.ivChecked.setVisibility(View.VISIBLE);
select_color = colorModelList.get(position).getAttName();
if( context instanceof AddToCartActivity){
((AddToCartActivity) context).getSelectedC0lor(select_color);
}
}
return convertView;
}
class ViewHolder{
#BindView(R.id.view)
LinearLayout view;
#BindView(R.id.tv_color_name)
TextViewHelper tvColorName;
#BindView(R.id.iv_image)
ImageView ivImage;
#BindView(R.id.iv_checked)
ImageView ivChecked;
public ViewHolder(View view) {
ButterKnife.bind(this,view);
}
}
}
MyCustomSizeRecylerAdapter.java
public class MyCustomSizeRecylerAdapter extends RecyclerView.Adapter<MyCustomSizeRecylerAdapter.MyViewHolder> {
ArrayList<SizeCustomModel> sizeModels;
Context context;
int checkPosition = -1;
String selectedSize;
public MyCustomSizeRecylerAdapter(ArrayList<SizeCustomModel> sizeModels, Context context) {
this.sizeModels = sizeModels;
this.context = context;
}
public void getNewModel(ArrayList<SizeCustomModel> customModels) {
sizeModels.clear();
this.sizeModels = customModels;
selectedSize = null;
Log.d("sizemodel", "getNewModel: " + new Gson().toJson(sizeModels));
notifyDataSetChanged();
}
public void getSelectedPosition(int position) {
checkPosition = position;
notifyDataSetChanged();
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.size_adapter, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.tv_sizeName.setText(sizeModels.get(position).getSize());
holder.ll_sizeAdapter.setBackgroundResource(R.drawable.ellipse_register);
if (sizeModels.get(position).getStock_Status() == 0) {
holder.ll_mainview.setClickable(false);
holder.ll_sizeAdapter.setBackgroundResource(R.color.blue_700);
} else if (sizeModels.get(position).getStock_Status() == 1) {
holder.ll_sizeAdapter.setBackgroundResource(R.drawable.ellipse_register);
if (checkPosition == position) {
holder.ll_sizeAdapter.setBackgroundResource(R.drawable.ellipse_green);
holder.tv_sizeName.setTextColor(context.getResources().getColor(R.color.white));
selectedSize = sizeModels.get(position).getSize();
if (context instanceof AddToCartActivity) {
((AddToCartActivity) context).getSelectSize(selectedSize);
}
} else {
holder.ll_sizeAdapter.setBackgroundResource(R.drawable.ellipse_register);
holder.tv_sizeName.setTextColor(context.getResources().getColor(R.color.tv_black));
}
if (sizeModels.size() == 1) {
holder.ll_sizeAdapter.setBackgroundResource(R.drawable.ellipse_green);
holder.tv_sizeName.setTextColor(context.getResources().getColor(R.color.white));
selectedSize = sizeModels.get(position).getSize();
if (context instanceof AddToCartActivity) {
((AddToCartActivity) context).getSelectSize(selectedSize);
}
}
}
}
#Override
public int getItemCount() {
return sizeModels.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.tv_sizeName)
TextView tv_sizeName;
#BindView(R.id.ll_sizeAdapter)
LinearLayout ll_sizeAdapter;
#BindView(R.id.main_view)
LinearLayout ll_mainview;
public MyViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
At first both adapter will set data and after click color item the size adapter must be change but it only changes when i click any of the item. adapter.notifyDataSetChanged() doesnt work here for me.
Both Adapter set
When i click color item but doesnt change size adapter
when i click size item only change size adapter
Use Interface to bridge with two adapter and communicate with each other.

Multiselection RecyclerView selects other items also

I want to implement a simple custom multiselection RecyclerView.
My problem is when I select the first CardView element in the screen, the tenth Card is also selected (When I select the second, the eleventh card is selected etc.). I have tried many different such as using `notifyItemChanged(pos) but I always end up to the same bug.
Here is the code if the my custom class.
public class StudentRecyclerAdapter extends RecyclerView.Adapter<StudentRecyclerAdapter.CustomViewHolder> {
private List<Student> studentListItemList;
private Context mContext;
private Students students;
private Set<Integer> studensToBeRemoved;
private List<Boolean> selected;
public StudentRecyclerAdapter(Context context, List<Student> studentListItemList, Students students) {
this.studentListItemList = studentListItemList;
this.mContext = context;
this.studensToBeRemoved = new HashSet<>();
this.students = students;
selected= new ArrayList<>();
for(int i=0;i<studentListItemList.size();i++)
selected.add(false);
}
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
CustomViewHolder holder = (CustomViewHolder) view.getTag();
int position = holder.getAdapterPosition();
Student studentListItem = studentListItemList.get(position);
Bundle extras = new Bundle();
extras.putInt("id", studentListItem.getId());
extras.putString("name", studentListItem.getName());
extras.putString("surname", studentListItem.getSurname());
extras.putLong("date", studentListItem.getLongBirthday());
extras.putString("photo", studentListItem.getImage());
Intent intent = new Intent(mContext, ProfileStudent.class);
intent.putExtras(extras);
mContext.startActivity(intent);
}
};
View.OnLongClickListener longClickListener = view -> {
final CustomViewHolder holder = (CustomViewHolder) view.getTag();
int pos = holder.getAdapterPosition();
if (!selected.get(pos)) {
holder.stud_card_view.setCardBackgroundColor(Color.GREEN);
studensToBeRemoved.add(studentListItemList.get(pos).getId());
selected.set(pos,true);
} else {
holder.stud_card_view.setCardBackgroundColor(Color.WHITE);
studensToBeRemoved.remove(studentListItemList.get(pos).getId());
selected.set(pos,false);
}
if (studensToBeRemoved.size() > 0)
students.onMethodCallback(true);
else
students.onMethodCallback(false);
StringBuilder stringBuilder= new StringBuilder();
for(Integer integer : studensToBeRemoved)
stringBuilder.append(integer).append(", ");
Toast.makeText(mContext,String.valueOf(pos)+ ": "+stringBuilder.toString(),Toast.LENGTH_LONG).show();
return true;
};
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.student_list_row, null);
RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
view.setLayoutParams(lp);
CustomViewHolder viewHolder = new CustomViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(CustomViewHolder customViewHolder, int i) {
}
#Override
public void onBindViewHolder(CustomViewHolder customViewHolder, int i, List<Object> payload) {
if (payload.size() == 1) {
if ((boolean) payload.get(0)) {
customViewHolder.stud_card_view.setCardBackgroundColor(Color.GREEN);
studensToBeRemoved.add(studentListItemList.get(i).getId());
} else {
customViewHolder.stud_card_view.setCardBackgroundColor(Color.WHITE);
studensToBeRemoved.remove(studentListItemList.get(i).getId());
}
if (studensToBeRemoved.size() > 0)
students.onMethodCallback(true);
else
students.onMethodCallback(false);
} else {
Student studentListItem = studentListItemList.get(i);
Picasso.with(mContext).load(studentListItem.getImage())
.error(R.drawable.placeholder)
.placeholder(R.drawable.placeholder)
.into(customViewHolder.imageView);
customViewHolder.textView.setText(studentListItem.getName() + " " + studentListItem.getSurname());
customViewHolder.stud_card_view.setTag(customViewHolder);
customViewHolder.stud_card_view.setOnClickListener(clickListener);
customViewHolder.stud_card_view.setOnLongClickListener(longClickListener);
}
}
#Override
public int getItemCount() {
return (null != studentListItemList ? studentListItemList.size() : 0);
}
public void setFilter(ArrayList<Student> newList) {
studentListItemList = new ArrayList<>();
studentListItemList.addAll(newList);
notifyDataSetChanged();
}
public Set<Integer> getStudensToBeRemoved() {
return studensToBeRemoved;
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
protected ImageView imageView;
protected TextView textView;
protected CardView stud_card_view;
public CustomViewHolder(View view) {
super(view);
this.imageView = view.findViewById(R.id.stud_list_pic);
this.textView = view.findViewById(R.id.stud_list_name);
this.stud_card_view = view.findViewById(R.id.stud_card_view);
}
}
}
PS. The payload check I have is because i have also implemented a selectAll() method (Which I call from the fragment host the RecyclerView) which uses the notifyItemRangeChanged() which is works properly.
Finally even the the 10th entry is also checked the studensToBeRemoved.add(studentListItemList.get(pos).getId()); for the 10th entry is never called actually. (The
Toast.makeText(mContext,String.valueOf(pos)+ ": "+stringBuilder.toString(),Toast.LENGTH_LONG).show();
in the end of onLongClickListener shows only the correct values every time ( e.g. when is select the first entry it shows "1: 1") although entry 10 is also selected). Finally if I select entry 10 the opposite happens (entry 1 is also selected).
Any Ideas whats going wrong? I can also provide some screenshots or more details if needed.
Thanks!
I managed to fix it. So here is the correct code in case someone wants to implement a simple RecyclerView with multi-selection. I hope it helps.
public class StudentRecyclerAdapter extends RecyclerView.Adapter<StudentRecyclerAdapter.CustomViewHolder> {
private List<Student> studentListItemList;
private Context mContext;
private StudentsFragment students;
private Set<Integer> studensToBeRemoved;
private List<Boolean> selected;
private View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
CustomViewHolder holder = (CustomViewHolder) view.getTag();
int pos = holder.getAdapterPosition();
if (studensToBeRemoved.size() == 0) {
Student studentListItem = studentListItemList.get(pos);
Bundle extras = new Bundle();
extras.putInt("id", studentListItem.getId());
extras.putString("name", studentListItem.getName());
extras.putString("surname", studentListItem.getSurname());
extras.putLong("date", studentListItem.getLongBirthday());
extras.putString("photo", studentListItem.getImage());
Intent intent = new Intent(mContext, ProfileStudent.class);
intent.putExtras(extras);
mContext.startActivity(intent);
} else {
if (!selected.get(pos)) {
holder.stud_card_view.setCardBackgroundColor(Color.GREEN);
studensToBeRemoved.add(studentListItemList.get(pos).getId());
selected.set(pos, true);
} else {
holder.stud_card_view.setCardBackgroundColor(Color.WHITE);
studensToBeRemoved.remove(studentListItemList.get(pos).getId());
selected.set(pos, false);
}
if (studensToBeRemoved.size() > 0)
students.onMethodCallback(true);
else
students.onMethodCallback(false);
}
}
};
private View.OnLongClickListener longClickListener = view -> {
final CustomViewHolder holder = (CustomViewHolder) view.getTag();
int pos = holder.getAdapterPosition();
if (!selected.get(pos)) {
holder.stud_card_view.setCardBackgroundColor(Color.GREEN);
studensToBeRemoved.add(studentListItemList.get(pos).getId());
selected.set(pos, true);
} else {
holder.stud_card_view.setCardBackgroundColor(Color.WHITE);
studensToBeRemoved.remove(studentListItemList.get(pos).getId());
selected.set(pos, false);
}
if (studensToBeRemoved.size() > 0)
students.onMethodCallback(true);
else
students.onMethodCallback(false);
return true;
};
public StudentRecyclerAdapter(Context context, List<Student> studentListItemList, Students students) {
this.studentListItemList = studentListItemList;
this.mContext = context;
this.studensToBeRemoved = new HashSet<>();
this.students = students;
selected = new ArrayList<>();
for (int i = 0; i < studentListItemList.size(); i++)
selected.add(false);
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.student_list_row, null);
RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
view.setLayoutParams(lp);
CustomViewHolder viewHolder = new CustomViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(CustomViewHolder customViewHolder, int i) {
Student studentListItem = studentListItemList.get(i);
Picasso.with(mContext).load(studentListItem.getImage())
.error(R.drawable.placeholder)
.placeholder(R.drawable.placeholder)
.into(customViewHolder.imageView);
customViewHolder.textView.setText(studentListItem.getName() + " " + studentListItem.getSurname());
customViewHolder.stud_card_view.setTag(customViewHolder);
customViewHolder.edit_button.setTag(customViewHolder);
customViewHolder.stud_card_view.setOnClickListener(clickListener);
if (!selected.get(i))
customViewHolder.stud_card_view.setCardBackgroundColor(Color.WHITE);
else
customViewHolder.stud_card_view.setCardBackgroundColor(Color.GREEN);
customViewHolder.stud_card_view.setOnLongClickListener(longClickListener);
customViewHolder.stud_card_view.setOnClickListener(clickListener);
customViewHolder.edit_button.setOnClickListener(clickListener);
}
#Override
public int getItemCount() {
return (null != studentListItemList ? studentListItemList.size() : 0);
}
public void setFilter(ArrayList<Student> newList) {
studentListItemList = new ArrayList<>();
studentListItemList.addAll(newList);
notifyDataSetChanged();
}
public Set<Integer> getStudensToBeRemoved() {
return studensToBeRemoved;
}
public void setSelected(boolean b) {
if (b) {
for (int i = 0; i < selected.size(); i++) {
studensToBeRemoved.add(studentListItemList.get(i).getId());
selected.set(i, true);
}
students.onMethodCallback(true);
} else {
for (int i = 0; i < selected.size(); i++) {
selected.set(i, false);
studensToBeRemoved.remove(studentListItemList.get(i).getId());
}
students.onMethodCallback(false);
}
notifyItemRangeChanged(0, getItemCount());
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
protected ImageView imageView;
protected TextView textView;
protected CardView stud_card_view;
protected ImageButton edit_button;
public CustomViewHolder(View view) {
super(view);
this.imageView = view.findViewById(R.id.stud_list_pic);
this.textView = view.findViewById(R.id.stud_list_name);
this.stud_card_view = view.findViewById(R.id.stud_card_view);
this.edit_button = view.findViewById(R.id.student_edit_btn);
edit_button.bringToFront();
}
}
}
The students.onMethodCallback() function informs the host fragment to show/hide the delete button. In order to select/deselect all element at once all you have to do is to call the setSelected(true/false) method.

findViewHolderForAdapterPosition returns null

I'm using SectionedRecyclerViewAdapter and i'm pass to myAdapter two sections
first section has 16 elements , and second section has 18 elements
each element has CheckBox Item and i'm try calling method that set all items as checked , but when looping on it and get item number 17 it returns null
but my mRecyclerView actually has 34 items as a total
so how to move to other section and get element number 17.
sectionAdapter = new SectionedRecyclerViewAdapter();
ArrayList<Item> contacts = new ArrayList<>();
// ArrayList<String> dishNames = new ArrayList<>();
mRecyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
for(int d = 0 ; d<DishesIngredientsShoppingList.size() ;d++) {
contacts = new ArrayList<>();
for (int i = 0; i < DishesIngredientsShoppingList.get(d).getGroups().length; i++) {
for (int g = 0; g < DishesIngredientsShoppingList.get(d).getGroups()[i].getIngredients().length; g++) {
contacts.add(new Item(DishesIngredientsShoppingList.get(d).getGroups()[i].getIngredients()[g].getName()));
}
}
sectionAdapter.addSection(new ContactsSection(DishesIngredientsShoppingList.get(d).getName(),contacts));
// contacts.clear();
}
class ContactsSection extends StatelessSection {
String title;
List<Item> list;
ItemViewHolder row;
HeaderViewHolder MainRow;
public ContactsSection(String title, ArrayList<Item> list) {
super(R.layout.shopping_row_item_header, R.layout.shopping_row_item);
this.title = title;
this.list = list;
}
#Override
public int getContentItemsTotal() {
return list.size(); // list here has 16 elements !! it should 34 elements
}
#Override
public RecyclerView.ViewHolder getItemViewHolder(View view) {
return new ItemViewHolder(view);
}
#Override
public void onBindItemViewHolder(final RecyclerView.ViewHolder holder, final int position) {
final ItemViewHolder itemHolder = (ItemViewHolder) holder;
final Item name = list.get(position);
itemHolder.tvItem.setText(name.name);
((ItemViewHolder) holder).IntegBOX.setChecked(name.checked);
chooseAllradioButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (int i = 0; i <sectionAdapter.getItemCount(); i++) {
final Item name = list.get(i);
name.checked = true;
sectionAdapter.notifyDataSetChanged();
}
}
});
#Override
public RecyclerView.ViewHolder getHeaderViewHolder(View view) {
return new HeaderViewHolder(view);
}
#Override
public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder) {
HeaderViewHolder headerHolder = (HeaderViewHolder) holder;
headerHolder.tvTitle.setText(title);
}
}
class HeaderViewHolder extends RecyclerView.ViewHolder {
private final TextView tvTitle;
private final CheckBox DishBOX;
public HeaderViewHolder(View view) {
super(view);
tvTitle = (TextView) view.findViewById(R.id.DishName);
DishBOX = (CheckBox) view.findViewById(R.id.chooseDish);
}
}
class ItemViewHolder extends RecyclerView.ViewHolder implements CompoundButton.OnCheckedChangeListener{
private final View rootView;
private final TextView tvItem;
private final CheckBox IntegBOX;
public ItemViewHolder(View view) {
super(view);
rootView = view;
tvItem = (TextView) view.findViewById(R.id.DishName);
IntegBOX = (CheckBox) view.findViewById(R.id.chooseDish);
IntegBOX.setOnCheckedChangeListener(this);
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int position = getAdapterPosition();
list.get(position).checked = isChecked;
}
}
}
class Item {
String name;
boolean checked;
public Item(String name) {
this.name = name;
checked = false;
}
}
Add a method in your ContactsSection class to check all items:
public void checkAllItems() {
for (Item item : list) {
item.checked = true;
}
}
Then change your onClick code to:
chooseAllradioButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for(Section section : sectionAdapter.getSectionsMap().values()) {
section.checkAllItems();
}
sectionAdapter.notifyDataSetChanged();
}
});

How to fetch the value from custom ExpandableList Adapter class and set into previous fragment of UI component

I have the following two class one is fragment class and another one is custom expandablelistadapter class. i want the values fetch from the expandablelistadapter class and set the values into fragment UI component like set into textview i describe as comment in following class where to taken values
and where to set the values
SlideContentFragment.java
public class SlidingContentFragment extends Fragment {
static final String LOG_TAG = "SlidingContentFragment";
// store category list from Conastant list, used for to display pagetitle
List<String> catList = AppConstants.CATEGORY_LIST;
private static String[] tmpId = {"35","36","41","42","43","44","45","46"};
ExpandableListView exListCategory;
private SlidingTabLayout mSlidingTabLayout;
/**
* A {#link android.support.v4.view.ViewPager} which will be used in conjunction with the {#link SlidingTabLayout} above.
*/
private ViewPager mViewPager;
//private ExpandableListAdapter mAdapter; // added new
private SamplePagerAdapter myAdapter;
public SlidingContentFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_sliding_content, container, false);
ImageButton cartImgBtn = (ImageButton)v.findViewById(R.id.imgBtnCart);
TextView totalCntItem = (TextView)v.findViewById(R.id.tvCartItemCount);
// I want here set the value of totalCounter from ExpandableList Adapter class when i click on plus
// OR minus button of particular item it updates its value as total count of all item selected
// here following line of code which not worked
totalCntItem.setText(String.format("%d",CategoryItemListAdapter.getTotalCounter()));
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// BEGIN_INCLUDE (setup_viewpager)
// Get the ViewPager and set it's PagerAdapter so that it can display items
this.myAdapter = new SamplePagerAdapter(); // added new
mViewPager = (ViewPager) view.findViewById(R.id.viewpager);
mViewPager.setAdapter(this.myAdapter);
// END_INCLUDE (setup_viewpager)
// BEGIN_INCLUDE (setup_slidingtablayout)
// Give the SlidingTabLayout the ViewPager, this must be done AFTER the ViewPager has had
// it's PagerAdapter set.
mSlidingTabLayout = (SlidingTabLayout) view.findViewById(R.id.sliding_tabs);
mSlidingTabLayout.setViewPager(mViewPager);
}
public class SamplePagerAdapter extends PagerAdapter {
public SamplePagerAdapter() {
super();
}
#Override
public int getCount() {
return catList.size();
}
#Override
public boolean isViewFromObject(View view, Object o){
return o == view;
}
#Override
public CharSequence getPageTitle(int position) {
return catList.get(position);
}
#Override
public int getItemPosition (Object object)
{
return PagerAdapter.POSITION_NONE;
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
//return super.instantiateItem(container, position);
ViewPager viewPager = (ViewPager)container;
View view = getActivity().getLayoutInflater().inflate(R.layout.pager_item,
container, false);
viewPager.addView(view);
exListCategory = (ExpandableListView)view.findViewById(R.id.myExpandableListView);
//exListCategory.setIndicatorBounds(10,20);
exListCategory.setDividerHeight(2);
if(ConnectionDetector.isInternetAvailable(getActivity())) {
new CategoryJSONAsyncTask().execute("http://..../api/Main/GetCateenOrderCategoryItemListDetail?CategoryID=" + tmpId[position].trim());
}else{
Utility.buildDialog(getActivity()).show();
}
Log.i(String.format("%s: POSITION", LOG_TAG), String.valueOf(position));
Log.i(String.format("%s: CATLIST", LOG_TAG),String.valueOf(catList.get(position)));
view.setTag(position);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
//viewpager
ViewPager viewPager = (ViewPager)container;
View view = (View) object;
view.getTag(position);
viewPager.removeView(view);
//((ViewPager) container).removeView((View) object);
}
}
public class CategoryJSONAsyncTask extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String result = "";
try {
HttpGet httppost = new HttpGet(params[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
return result;
}
return result;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ArrayList<CategoryParentItemList> listParent = fetchResponse(result.replace("\n","").trim());
/*for (Object obj : listParent){
if(obj.getClass() == CategoryParentItemList.class){
CategoryParentItemList p = (CategoryParentItemList)obj;
System.out.println("P-ItemName: "+ p.subCategoryName);
}
}*/
CategoryItemListAdapter adapter = new CategoryItemListAdapter(SlidingContentFragment.this.getActivity(), listParent);
exListCategory.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
public ArrayList<CategoryParentItemList> fetchResponse(String result)
{
ArrayList<CategoryParentItemList> listParent = new ArrayList<>();
if (!result.equals(""))
{
try
{
JSONObject jsono = new JSONObject(result);
JSONArray jarray = jsono.getJSONArray("SBL");
CategoryParentItemList parent;
for (int i = 0; i < jarray.length(); i++)
{
ArrayList<CategoryChildListItem> childrens = new ArrayList<>();
childrens.clear();
CategoryChildListItem child;
JSONObject object = jarray.getJSONObject(i);
//System.out.println("SCI: " + object.getInt("SubCategoryID"));
//System.out.println("SCN: " + object.getString("SubCategoryName"));
JSONArray subItemArray = object.getJSONArray("SubCategoryItemList");
if (subItemArray.length() > 0)
{
for (int j = 0; j < subItemArray.length(); j++)
{
JSONObject subItemObject = subItemArray.getJSONObject(j);
String strItemName = subItemObject.getString("ItemName");
String strDefaultPrice = subItemObject.getString("DefaultPrice");
child = new CategoryChildListItem(strItemName, strDefaultPrice);
childrens.add(child);
//Log.i("strItemName", strItemName);
//Log.i("strDefaultPrice", strDefaultPrice);
}
parent = new CategoryParentItemList(object.getString("SubCategoryName"),childrens);
listParent.add(parent);
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
return listParent;
}
}
CategoryListItemAdaptor.java
public class CategoryItemListAdapter extends BaseExpandableListAdapter{
private Context context;
public static int totalCounter=0;
private ArrayList<CategoryParentItemList> listParent;
static class ViewHolderGroup {
public TextView lblSubCategoryName;
}
static class ViewHolderChild {
public TextView lblItemName;
public TextView lblDefualtPrice;
public TextView lblQty;
public ImageButton imgPlus;
public ImageButton imgMinus;
}
public CategoryItemListAdapter(Context context, ArrayList<CategoryParentItemList> listParent) {
super();
this.context = context;
this.listParent = listParent;
}
#Override
public int getGroupCount() {
return listParent.size();
}
#Override
public int getChildrenCount(int groupPosition) {
ArrayList<CategoryChildListItem> ch = listParent.get(groupPosition).getChildList();
return ch.size();
}
#Override
public Object getGroup(int groupPosition) {
return listParent.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
ArrayList<CategoryChildListItem> ch = listParent.get(groupPosition).getChildList();
return ch.get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
//CategoryParentItemList parentItem = (CategoryParentItemList)listParent.get(groupPosition);
CategoryParentItemList parentItem = (CategoryParentItemList) getGroup(groupPosition);
ViewHolderGroup holderGroup;
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.group_header, null);
holderGroup = new ViewHolderGroup();
holderGroup.lblSubCategoryName = (TextView) convertView.findViewById(R.id.tvItemName);
convertView.setTag(holderGroup);
} else {
holderGroup = (ViewHolderGroup) convertView.getTag();
}
holderGroup.lblSubCategoryName.setText(parentItem.getSubCategoryName());
return convertView;
}
#Override
public View getChildView(int groupPosition,int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
//final CategoryParentItemList parentItem = (CategoryParentItemList) listParent.get(groupPosition);
//final CategoryChildListItem childItem = (CategoryChildListItem) parentItem.getChildList().get(childPosition);
CategoryChildListItem childItem = (CategoryChildListItem) getChild(groupPosition, childPosition);
ViewHolderChild holder;
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.child_row, null);
holder = new ViewHolderChild();
holder.lblItemName = (TextView) convertView.findViewById(R.id.tvSubItemName);
holder.lblDefualtPrice = (TextView) convertView.findViewById(R.id.tvrRupees);
holder.lblQty = (TextView) convertView.findViewById(R.id.tvQty);
holder.imgPlus = (ImageButton) convertView.findViewById(R.id.imageButtonPlus);
holder.imgMinus = (ImageButton) convertView.findViewById(R.id.imageButtonMinus);
convertView.setTag(holder);
} else {
holder = (ViewHolderChild) convertView.getTag();
}
holder.lblItemName.setText(childItem.getSubItemName());
holder.lblDefualtPrice.setText(childItem.getDefaultPrice());
int tmpCount = Integer.parseInt(holder.lblQty.getText().toString());
holder.imgPlus.setOnClickListener(new ClickUpdateListener(childItem,holder, tmpCount));
holder.imgMinus.setOnClickListener(new ClickUpdateListener(childItem,holder, tmpCount));
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
#Override
public boolean areAllItemsEnabled() {
return true;
}
public static int getTotalCounter() {
return totalCounter;
}
private class ClickUpdateListener implements View.OnClickListener {
ViewHolderChild holder;
public CategoryChildListItem childItem;
int counter = 0;
String counterMin;
public ClickUpdateListener(CategoryChildListItem childItem,ViewHolderChild holder, int cnt) {
this.childItem = childItem;
this.holder = holder;
this.counter = cnt;
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.imageButtonPlus) {
counter = counter + 1;
totalCounter+=1;
System.out.println(childItem.getSubItemName()+" : "+childItem.getDefaultPrice() + ": C+ :" + counter);
holder.lblQty.setText(String.format("%d", counter));
notifyDataSetChanged();
}
if(v.getId() == R.id.imageButtonMinus){
counterMin = (String) holder.lblQty.getText();
counter = Integer.parseInt(counterMin.toString().trim());
counterMin = null;
if(counter > 0) {
counter = counter - 1;
totalCounter-=1;
System.out.println(childItem.getSubItemName()+" : "+childItem.getDefaultPrice() + ": C- :" + counter);
holder.lblQty.setText(String.format("%d", counter));
notifyDataSetChanged();
}else{
Toast.makeText(context,"Qty Zero",Toast.LENGTH_SHORT).show();
}
}
}
}
}

Categories