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.
Related
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.
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.
I have pass position in recyclerView click but some kind of problem pass to position to display wrong data so how can i pass people id in recyclerView.
I m new in android programming
recyclerView Item Click
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
buildCustomAdapter = new BuildCustomAdapter(this, peopleList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
buildCustomAdapter.notifyDataSetChanged();
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(buildCustomAdapter);
buildCustomAdapter.setOnItemClickListener(new BuildCustomAdapter.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
detailPeople(position);
}
});
private void detailPeople(int position) {
Intent intent = new Intent(this, AddDetail.class);
intent.putExtra("peopleID", position);
startActivity(intent);
}
Model.class
public class People implements Serializable {
private String peopleImage;
private String peopleName;
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setPeopleName(String peopleName) {
this.peopleName = peopleName;
}
public String getPeopleName() {
return peopleName;
}
public void setPeopleImage(String peopleImage) {
this.peopleImage = peopleImage;
}
public String getPeopleImage() {
return peopleImage;
}
}
Adapter code
public class BuildCustomAdapter extends RecyclerView.Adapter<BuildCustomAdapter.MyViewHolder> implements Filterable {
private List<People> peopleList;
private List<People> peopleListCopy;
private ItemFilter mFilter = new ItemFilter();
private OnItemClickListener mOnItemClickListener;
private Context mContext;
public BuildCustomAdapter(Context context, List<People> buildList) {
mContext = context;
this.peopleList = buildList;
this.peopleListCopy = new ArrayList<>();
peopleListCopy.addAll(buildList);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.build_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
People people = peopleList.get(position);
byte[] decodedString = Base64.decode(people.getPeopleImage(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
holder.ivPeopleImage.setImageBitmap(decodedByte);
holder.tvPersonName.setText(people.getPeopleName());
holder.button.setSelected(people.getStatus() == 1);
holder.button.setOnClickListener(new onSelectListener(position));
}
#Override
public int getItemCount() {
return peopleList.size();
}
#Override
public Filter getFilter() {
if (mFilter == null) {
mFilter = new ItemFilter();
}
return mFilter;
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView tvPersonName;
public Button button;
public CircularImageView ivPeopleImage;
public MyViewHolder(View itemView) {
super(itemView);
mContext = itemView.getContext();
ivPeopleImage = (CircularImageView) itemView.findViewById(R.id.ivPerson);
tvPersonName = (TextView) itemView.findViewById(R.id.tvPersonName);
button = (Button) itemView.findViewById(R.id.addbn);
tvPersonName.setOnClickListener(this);
ivPeopleImage.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (mOnItemClickListener != null)
mOnItemClickListener.onItemClick(v, getPosition());
}
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
mOnItemClickListener = onItemClickListener;
}
public interface OnItemClickListener {
void onItemClick(View view, int position);
}
private class ItemFilter extends Filter {
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
List<People> filterList = new ArrayList<>();
for (int i = 0; i < peopleListCopy.size(); i++) {
if ((peopleListCopy.get(i).getPeopleName().toUpperCase())
.contains(constraint.toString().toUpperCase())) {
People peopleName = peopleListCopy.get(i);
filterList.add(peopleName);
}
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = peopleListCopy.size();
results.values = peopleListCopy;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
peopleList = (List<People>) results.values;
notifyDataSetChanged();
}
}
private class onSelectListener implements View.OnClickListener {
int mPosition;
public onSelectListener(int position) {
mPosition = position;
}
#Override
public void onClick(View view) {
People people = peopleList.get(mPosition);
view.setSelected(!view.isSelected());
people.setStatus(view.isSelected() ? 1 : 0);
notifyDataSetChanged();
}
}
}
Next Activity to get intent
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
int peopleID = bundle.getInt("peopleID");
peopleList.clear();
BuildDataa();
People peopleDetailsObj = peopleList.get(peopleID);
}
Please replace
#Override
public void onClick(View v) {
if (mOnItemClickListener != null)
mOnItemClickListener.onItemClick(v, getPosition());
}
to
#Override
public void onClick(View v) {
if (mOnItemClickListener != null)
mOnItemClickListener.onItemClick(v, peopleList.get(getPosition()).getId());
}
in your adapter. And change signature of method onItemClick from
onItemClick(View v, int position)
to
onItemClick(View v, String id)
and use this to get People according to ID
People peopleDetailsObj=null;
for(People ple:peopleList)
{
if(ple.getId().equals(peopleID)){
peopleDetailsObj=ple;
break;
}}
Take the id from position.
String id=peopleList.get(position).getId();
detailPeople(id);
Pass that id in your method and you are done.
Use position to get People object from ArrayList. Change detailPeople() method with below code.
private void detailPeople(int position) {
Intent intent = new Intent(this, AddDetail.class);
intent.putExtra("peopleID", peopleList.get(position).getId());
startActivity(intent);
}
intent.putExtra("id", peopleList.get(position).getId());
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();
}
});
My code is working fine when it comes to clicking items. But the problem arises when I try to open activities after filtering listview. It always opens activity 1.
Here is my source code.
navigate.java
public class navigate extends Activity {
// Declare Variables
ListView list;
ListViewAdapter adapter;
EditText editsearch;
String[] rank;
String[] names;
int[] flag;
ArrayList<Object> arraylist = new ArrayList<Object>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_main);
// Generate sample data
rank = new String[] { "1", "2", "3", "4", "5","6","7","8","9","10","11"};
names = new String[] { "Animal Bite", "Asthma Attack", "Choking","CPR","Black eye",
"Drowning", "Fracture","Heart Attack","Insect Bite","Poisoning","Spinal Injury",};
flag = new int[] { R.drawable.animal,
R.drawable.asthma, R.drawable.choke, R.drawable.cpricon,
R.drawable.blckeye,R.drawable.drown,R.drawable.fracture,R.drawable.hrtattck,R.drawable.insect,R.drawable.poison,R.drawable.spinal };
// Locate the ListView in listview_main.xml
list = (ListView) findViewById(R.id.listview);
for (int i = 0; i < rank.length; i++)
{
Object wp = new Object(rank[i], names[i], flag[i]);
// Binds all strings into an array
arraylist.add(wp);
}
// Pass results to ListViewAdapter Class
adapter = new ListViewAdapter(this, arraylist);
// Binds the Adapter to the ListView
list.setAdapter(adapter);
// Locate the EditText in listview_main.xml
editsearch = (EditText) findViewById(R.id.search);
// Capture Text in EditText
editsearch.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = editsearch.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(final AdapterView<?> listView, View view,
final int position, long id) {
switch ((int) adapter.getItemId(position)) {
case 0:
Intent newActivity = new Intent(navigate.this, animalbite.class);
startActivity(newActivity);
break;
case 1:Intent newActivity1 = new Intent(navigate.this, asthmaattack.class);
startActivity(newActivity1);
break;
case 2:Intent newActivity2 = new Intent(navigate.this, animalbite.class);
startActivity(newActivity2);
break;}
}
});
}
}
ListViewAdapter.java
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<Object> objectList = null;
private ArrayList<Object> arraylist;
public ListViewAdapter(Context context,
List<Object> objectList) {
mContext = context;
this.objectList = objectList;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<Object>();
this.arraylist.addAll(objectList);
}
public class ViewHolder {
TextView name;
ImageView flag;
}
#Override
public int getCount() {
return objectList.size();
}
#Override
public Object getItem(int position) {
return objectList.get(position);
}
public String getCountry(int position){return objectList.get(position).getCountry();}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
// Locate the TextViews in listview_item.xml
//holder.rank = (TextView) view.findViewById(R.id.rank);
holder.name = (TextView) view.findViewById(R.id.name);
// Locate the ImageView in listview_item.xml
holder.flag = (ImageView) view.findViewById(R.id.flag);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
//holder.rank.setText(objectList.get(position).getRank());
holder.name.setText(objectList.get(position).getCountry());
;
// Set the results into ImageView
holder.flag.setImageResource(objectList.get(position)
.getFlag());
// Listen for ListView Item Click
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Send single item click data to SingleItemView Class
// Pass all data rank
// Start SingleItemView Class
switch (position) {
case 0:
Intent intent = new Intent(mContext, animalbite.class);
mContext.startActivity(intent);break;
case 1:
Intent i2 = new Intent(mContext, asthmaattack.class);
mContext.startActivity(i2);break;
case 2:
Intent i3 = new Intent(mContext, choking.class);
mContext.startActivity(i3);break;
case 3:
Intent i4 = new Intent(mContext, cpr.class);
mContext.startActivity(i4);break;
case 4:
Intent i5 = new Intent(mContext, lackeye.class);
mContext.startActivity(i5);break;
case 5:
Intent i6 = new Intent(mContext, drowning.class);
mContext.startActivity(i6);break;
case 6:
Intent i7 = new Intent(mContext, Fracture.class);
mContext.startActivity(i7);break;
case 7:
Intent i8 = new Intent(mContext, heartattack.class);
mContext.startActivity(i8);break;
case 8:
Intent i9 = new Intent(mContext, insectbite.class);
mContext.startActivity(i9);break;
case 9:
Intent i10 = new Intent(mContext, poisoning.class);
mContext.startActivity(i10);break;
case 10:
Intent i11 = new Intent(mContext, spinalinjury.class);
mContext.startActivity(i11);break;
}}});
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
objectList.clear();
if (charText.length() == 0) {
objectList.addAll(arraylist);
} else {
for (Object wp : arraylist) {
if (wp.getCountry().toLowerCase(Locale.getDefault())
.contains(charText)) {
objectList.add(wp);
}
}
}
notifyDataSetChanged();
}
}
Object.java
public class Object {
private String rank;
private String country;
private int flag;
public Object(String rank, String country,
int flag) {
this.rank = rank;
this.country = country;
this.flag = flag;
}
public String getCountry() {
return this.country;
}
public int getFlag() {
return this.flag;
}
}
How can I open different activities while clicking on listview items after I filter them.
This is the sample code I used. Although it doesn't provide the functionality to open original activities through intent ,just some forged up activity,so I'm trying to change that.
http://www.androidbegin.com/tutorial/android-search-filter-listview-images-and-texts-tutorial/
I think your adapter has problem, this below sample code of my application is extended from Filterable and work fine
public class AdapterContacts extends BaseAdapter implements Filterable {
private LayoutInflater inflater;
private Context context;
private List<ContactLists> categoryArrayList;
private final ArrayList<ContactLists> originalList = new ArrayList<ContactLists>();
private NameFilter filter;
public AdapterContacts(ArrayList<ContactLists> array) {
categoryArrayList = array;
}
public AdapterContacts(Context context, List<ContactLists> array) {
this.context = context;
inflater = LayoutInflater.from(this.context);
categoryArrayList = array;
originalList.addAll(array);
}
#Override
public int getCount() {
return categoryArrayList.size();
}
#Override
public ContactLists getItem(int position) {
return categoryArrayList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder mViewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.layout_contacts_list_item, null);
mViewHolder = new ViewHolder(convertView);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (ViewHolder) convertView.getTag();
}
ContactLists item = getItem(position);
mViewHolder.fillItems(this, item, position);
return convertView;
}
private static class UI extends HelperUI {
public TextView tv_person_nickname_mobile_number;
public TextView btn_invite_message;
public ImageView img_contact_image;
public ImageView imgv_user_rank;
public TextView tv_contact_name;
public LinearLayout ll_root;
public UI(View view) {
parseUi(view);
}
}
private class ViewHolder {
private UI UI;
public ViewHolder(View view) {
UI = new UI(view);
}
public void fillItems(final AdapterContacts adapter, final ContactLists item, final int position) {
UI.tv_contact_name.setText(item.getContact_name());
if (item.getStatus() == 1) {
UI.btn_invite_message.setVisibility(View.GONE);
UI.imgv_user_rank.setVisibility(View.VISIBLE);
if (item.getRank() != null || !TextUtils.isEmpty(item.getRank())) {
//Picasso.with(G.context).load(item.getRank()).into(UI.imgv_user_rank);
}
UI.tv_person_nickname_mobile_number.setText(item.getNick_name());
//UI.ll_root.setBackgroundDrawable(G.context.getResources().getDrawable(R.drawable.selector_button_actions));
if (item.getContact_image() == null || TextUtils.isEmpty(item.getContact_image())) {
Bitmap bitmap = UC.getContactPhoto(item.getMobile_number(), G.context.getContentResolver());
if (bitmap != null) {
UI.img_contact_image.setImageBitmap(bitmap);
} else {
UI.img_contact_image.setImageDrawable(G.context.getResources().getDrawable(R.drawable.no_avatar));
}
} else {
// show user avatar from web
//Picasso.with(G.context).load(item.getContact_image()).into(UI.img_contact_image);
UI.img_contact_image.setImageBitmap(BitmapFactory.decodeFile(G.DIR_IMAGE + "/" + item.getContact_image()));
}
} else {
// UI.ll_root.setBackgroundDrawable(G.context.getResources().getDrawable(R.drawable.selector_invite_actions));
UI.btn_invite_message.setVisibility(View.VISIBLE);
UI.imgv_user_rank.setVisibility(View.GONE);
UI.btn_invite_message.setText(UC.getString(R.string.invite_person));
UI.btn_invite_message.setBackgroundDrawable(G.context.getResources().getDrawable(R.drawable.shape_invite_button_default));
UI.tv_person_nickname_mobile_number.setText(item.getMobile_number());
Bitmap bitmap = UC.getContactPhoto(item.getMobile_number(), G.context.getContentResolver());
if (bitmap != null) {
UI.img_contact_image.setImageBitmap(bitmap);
} else {
UI.img_contact_image.setImageDrawable(G.context.getResources().getDrawable(R.drawable.no_avatar));
}
}
}
}
#Override
public Filter getFilter() {
if (filter == null) {
filter = new NameFilter();
}
return filter;
}
public class NameFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
String searchText = constraint.toString().toLowerCase();
ArrayList<ContactLists> newList = filterListBasedOnSearchText(searchText);
results.values = newList;
results.count = newList.size();
return results;
}
private ArrayList<ContactLists> filterListBasedOnSearchText(String constraint) {
ArrayList<ContactLists> newList = new ArrayList<ContactLists>();
int l = originalList.size();
for (int i = 0; i < l; i++) {
ContactLists nameList = originalList.get(i);
if (nameList.getContact_name().toString().contains(constraint)) {
newList.add(nameList);
}
}
return newList;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
categoryArrayList = (ArrayList<ContactLists>) results.values;
notifyDataSetChanged();
}
}
}