Android Checkbox in Listview selecting automatically - java

in my android application I am displaying the contact list of phone in a list view and a check box in each row for selecting contacts. But when I am selecting a particular row about tenth row is also getting selected automatically. I am giving my code below, if any one knows please help..
public class ContactsAdapter extends BaseAdapter
{
private Context context;
private ArrayList<Contact> contacts;
public ContactsAdapter(Context context, ArrayList<Contact> contacts)
{
this.context = context;
this.contacts = contacts;
}
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
final ViewHolder mHolder;
if (convertView == null)
{
// gridView = new View(context);
// get layout from mobile.xml
//gridView = inflater.inflate(R.layout.contact, null);
convertView = inflater.inflate(R.layout.contact, null);
mHolder = new ViewHolder();
mHolder.textName =(TextView) convertView.findViewById(R.id.name);
mHolder.textMobile =(TextView) convertView.findViewById(R.id.mobile);
mHolder.textSelector =(CheckBox) convertView.findViewById(R.id.selected);
convertView.setTag(mHolder);
));
}
else
{
mHolder = (ViewHolder) convertView.getTag();
mHolder.textSelector.setOnCheckedChangeListener(null);
}
mHolder.textMobile.setText(contacts.get(position).getMobile());
mHolder.textName.setText(contacts.get(position).getName());
mHolder.textSelector.setFocusable(false);
return convertView;
}
private class ViewHolder {
private TextView textMobile,textName;
private CheckBox textSelector;
}
#Override
public int getCount() {
return contacts.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
}

Well Thats because ViewHolder will recycle the Views everytime you Scroll
i suggest you to Use onCLick on ListItem instead checkbox
To overcome this Declare a SparseBooleanArray
SparseBooleanArray sba=new SparseBooleanArray();//this should be global
Then set the items checked state as soon as you render it
mHolder.textSelector =(CheckBox) convertView.findViewById(R.id.selected);
mHolder.textSelector.setChecked(sba.get(position));
Then write a onClickListener to you convertView and check it manually
convertView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
mHolder.textSelector.setChecked(isChecked);
sba.put(position,isChecked); //storing the state
}
}
);
**Well Now the sba has list items checked and you can use that for further Actions**

# Jocheved... edit your code like this...
public class ContactsAdapter extends BaseAdapter
{
private Context context;
private ArrayList<Contact> contacts;
SparseBooleanArray sba=new SparseBooleanArray();
public ContactsAdapter(Context context, ArrayList<Contact> contacts)
{
this.context = context;
this.contacts = contacts;
}
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final ViewHolder mHolder;
if (convertView == null)
{
convertView = inflater.inflate(R.layout.contact, null);
mHolder = new ViewHolder();
mHolder.textName =(TextView) convertView.findViewById(R.id.name);
mHolder.textMobile =(TextView) convertView.findViewById(R.id.mobile);
mHolder.textSelector =(CheckBox) convertView.findViewById(R.id.selected);
convertView.setTag(mHolder);
}
else
{
mHolder = (ViewHolder) convertView.getTag();
}
mHolder.textMobile.setText(contacts.get(position).getMobile());
mHolder.textName.setText(contacts.get(position).getName());
mHolder.textName.setSelected(true);
mHolder.textSelector.setChecked(sba.get(position));
mHolder.textSelector.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
if(mHolder.textSelector.isChecked())
{
sba.put(position, true);
}
else
{
sba.put(position, false);
}
}
});
return convertView;
}
private class ViewHolder
{
private TextView textMobile,textName;
private CheckBox textSelector;
}
#Override
public int getCount() {
return contacts.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
}

Related

Checkbox not saving when reopening

I have 3 classes relating to my checkbox section of my app in Android studio, atm the check box loads, but when selecting and deselecting the value doesn't save when I go bak into it from the main menu. any help would great!!!
public class WatchList extends AppCompatActivity {
ArrayList dataModels;
ListView listView;
private WatchListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i("watchlist", "created watchlist activity");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_watch_list);
listView = (ListView) findViewById(R.id.listview2);
dataModels = new ArrayList();
dataModels.add(new WatchListClass(R.drawable.kookaburra,"Kookaburra","Albury", false));
dataModels.add(new WatchListClass(R.drawable.cockatoo, "Cockatoo" , "Bathurst", true));
dataModels.add(new WatchListClass(R.drawable.emu,"Emu", "Echuca", true));
dataModels.add(new WatchListClass(R.drawable.magpie, "Magpie", "Sydney", true));
adapter = new WatchListAdapter(dataModels, getApplicationContext());
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
WatchListClass dataModel= (WatchListClass) dataModels.get(position);
dataModel.checked = !dataModel.checked;
adapter.notifyDataSetChanged();
}
});
}
}
public class WatchListAdapter extends ArrayAdapter {
private ArrayList dataSet;
Context mContext;
private static class ViewHolder {
TextView birdWatchName, birdWatchLocation;
ImageView birdWatchImage;
CheckBox checkBox;
}
public WatchListAdapter(ArrayList data, Context context) {
super(context, R.layout.watch_list, data);
this.dataSet = data;
this.mContext = context;
}
#Override
public int getCount() {
return dataSet.size();
}
#Override
public WatchListClass getItem(int position) {
return (WatchListClass) dataSet.get(position);
}
#Override
public View getView(int position, View convertView, #NonNull ViewGroup parent) {
ViewHolder viewHolder;
final View result;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.watch_list, parent, false);
viewHolder.birdWatchImage = (ImageView) convertView.findViewById(R.id.birdWatchImage);
viewHolder.birdWatchName = (TextView) convertView.findViewById(R.id.birdWatchName);
viewHolder.birdWatchLocation = (TextView) convertView.findViewById(R.id.birdWatchLocation);
viewHolder.checkBox = (CheckBox) convertView.findViewById(R.id.checkbox);
result=convertView;
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
result=convertView;
}
WatchListClass item = getItem(position);
viewHolder.birdWatchImage.setImageResource(item.birdWatchImage);
viewHolder.birdWatchName.setText(item.birdWatchName);
viewHolder.birdWatchLocation.setText(item.birdWatchLocation);
viewHolder.checkBox.setChecked(item.checked);
return result;
}
}
public class WatchListClass {
public String birdWatchName, birdWatchLocation;
int birdWatchImage;
boolean checked;
WatchListClass(int birdWatchImage, String birdWatchName,String birdWatchLocation, boolean checked) {
this.birdWatchName = birdWatchName;
this.birdWatchLocation = birdWatchLocation;
this.birdWatchImage = birdWatchImage;
this.checked = checked;
}
}
u can user shared preferences for check Box
try this one
How to save checkbox value with shared preferences?
you can use local database in app to store check box values and retrieve it back.

How to change the background color of a list item at click on a button?

I have a ListView and a CustomAdapter. The elements are all successfully loaded into the list. Now I want to change the background color of a certain element of the list by clicking on an external button. But I do not know how to access a specific item in the list.
Here is the CustomAdapter class:
public class CustomAdapter extends BaseAdapter {
private Context ctx;
private int resource;
private List<ItemModel> items;
public PreorderListAdapter(Context context, int resource, List<ItemModel> items){
this.ctx = context;
this.resource = resource;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public ItemModel getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#NonNull
#Override
public View getView(int i, View convertView, #NonNull ViewGroup parent) {
View view = convertView;
if(view == null){
LayoutInflater inflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(resource, null);
}
TextView text1 = (TextView) view.findViewById(R.id.text1);
TextView text2 = (TextView) view.findViewById(R.id.text2);
TextView text3 = (TextView) view.findViewById(R.id.text3);
ItemModel item = items.get(i);
text1.setText(item.getName());
text2.setText(item.getOption2());
text3.setText(item.getOption3());
return view;
}
}
You can do it like this inside your getView() method
view.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
view.setBackgroundColor(ContextCompat.getColor(this, R.color.yourcolor));
}
});
If you have a button on your view then performs the listener on that button
If you want to get your selected item view from your parent activity then :
yourlistview.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent,View view, int position, long id)
{
selectedposition = position ;
}
});
View view = listView.getAdapter().getView(selectedposition,null,listview);
Then change its background:
view.setBackgroundColor(ContextCompat.getColor(this, R.color.yourcolor));
please define your color in your color.xml file
If you have more than one view then , create an ArrayList<View> and do some loop
create a custom listener interface in your activity and your
adapter will implement this.
public interface OnClickListenerFromActivity {
void onActivityButtonClick(int position);
}
on click in your button call your listener's method
mOnClickListenerFromActivity.onActivityButtonClick(mList.getItem(yourPostion));
implement this listener into your adapter
public class CustomAdapter extends BaseAdapter implements Activity.OnClickListenerFromActivity {
private Context ctx;
private int resource;
private List<ItemModel> items;
public PreorderListAdapter(Context context, int resource, List<ItemModel> items){
this.ctx = context;
this.resource = resource;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public ItemModel getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#NonNull
#Override
public View getView(int i, View convertView, #NonNull ViewGroup parent) {
View view = convertView;
if(view == null){
LayoutInflater inflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(resource, null);
}
TextView text1 = (TextView) view.findViewById(R.id.text1);
TextView text2 = (TextView) view.findViewById(R.id.text2);
TextView text3 = (TextView) view.findViewById(R.id.text3);
ItemModel item = items.get(i);
text1.setText(item.getName());
text2.setText(item.getOption2());
text3.setText(item.getOption3());
return view;
}
public void onActivityButtonClick(int position) {
// get your item through position and
// set your color here
}
}

Android - Images changing on GridView when scrolling

I am trying to create a custom adapter for a shop element in my Android app but every time I scroll down the list the images seem to change their position, I have had a look around on here already but suggestions that I have found and tried have been to no avail.
Each item has a title, an image (being loading via an AsyncTask or retrieved from the LRUCache) and a price of the item below is the code I use to generate the adapter.
public class ShopAdapter extends BaseAdapter {
public Context context;
public ArrayList<ShopItem> shopItemList;
public ImageCache imageCache;
String imageToLoad;
Bitmap shopImage;
public ShopAdapter(Context context, ArrayList<ShopItem> shopItemList) {
this.context = context;
this.shopItemList = shopItemList;
imageCache = new ImageCache(this.context);
}
#Override
public int getCount() {
return shopItemList.size();
}
#Override
public Object getItem(int position) {
return shopItemList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView == null){
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.shop_list, null);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.textView3);
holder.image =(ImageView) convertView.findViewById(R.id.imageView);
holder.price = (TextView) convertView.findViewById(R.id.textView4);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.title.setText(shopItemList.get(position).getTitle());
shopImage = imageCache.getBitmapFromMemoryCache(shopItemList.get(position).getImage());
if(shopImage != null) {
holder.image.setImageBitmap(shopImage);
} else {
new LoadImage(context, holder.image).execute(imageToLoad);
}
holder.price.setText(shopItemList.get(position).getPrice());
return convertView;
}
static class ViewHolder {
TextView title;
ImageView image;
TextView price;
}
}
Any help would be very much appreciated!

change label text on button click inside a listview item

I have a listview item with a label and two buttons. I tried to change the label on button click. But it's changing text on another listview item. Not the label with button. I did this using a custom list adapter. I tried it like following,
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final MenuItem listItem = objects.get(position);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.menu_list_item, null);
btnPlus = (ButtonRectangle) convertView.findViewById(R.id.buttonPlus);
btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int i = 0;
cartQtyTextView.setText("" + ++i);
}
});
}
}
How may I fix this?
You might want to create holder.
I didn't include your menu item code due to i didn't see you got use it.
public class Holder {
ButtonRectangle buttonPlus;
TextView cartQtyTextView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get Holder
final Holder holder = new Holder();
// Change Layout
LayoutInflater inflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.menu_list_item, null);
// Find Control
holder.buttonPlus = (ButtonRectangle)view.findViewById(R.id.buttonPlus);
holder.cartQtyTextView = (TextView)view.findViewById(R.id.cartQtyTextView);
// Check & Set
if (holder.buttonPlus != null) {
holder.buttonPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int i = 0;
if (holder.cartQtyTextView != null) {
holder.cartQtyTextView.setText("" + ++i);
}
}
});
}
return view;
}
This is because you are setting the listener inside the if(convertView==null).
So the listener is only set once a view is created, but when you scroll, the list view is reusing a hidden item, but it keep the first assigned listener since the convertView is not null.
You need to set your onClickListener outside the if. And it is better if you use a holder for better performances
public class ExampleAdapter extends ArrayAdapter<MenuItem> {
private Activity activity;
private int resource;
private List<MenuItem> objects;
public ExampleAdapter(Activity activity, int resource, List<MenuItem> objects) {
super(activity, resource, objects);
this.activity = activity;
this.resource = resource;
this.objects= objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MenuItem listItem = objects.get(position);
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater li = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = li.inflate(resource, parent, false);
holder.labelTextView= (TextView) convertView.findViewById(R.id.labelTextView);
holder.btnPlus= (ButtonRectangle) convertView.findViewById(R.id.buttonPlus);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int i = 0;
holder.labelTextView.setText("" + ++i);
}
});
return convertView;
}
static class ViewHolder {
TextView labelTextView;
ButtonRectangle btnPlus;
}
}

When I scroll down or up the check position will be change every time

When I am checked any item like (position 0) its automatically checked randomly any item (like position 7) and when I scroll down or up the check position will be change every time... I am fed up from that problem...??
public class contactAdpter extends ArrayAdapter<ContactItem> {
Context context;
List<ContactItem> list;
public contactAdpter(Context context, int resource, List<ContactItem> items) {
super(context, resource,items);
this.context = context;
this.list = items;
}
static class ViewHolder {
ImageView imageview;
TextView tv1;
TextView tv2;
CheckBox ch;
}
#Override
public int getCount() {
return list.size();
}
#Override
public int getPosition(ContactItem item) {
return super.getPosition(item);
}
#Override
public long getItemId(int id) {
return id;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder=null;
View view = convertView;
ContactItem contactItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
view = mInflater.inflate(R.layout.contact_list, null);
holder = new ViewHolder();
holder.tv1 = (TextView) view.findViewById(R.id.name);
holder.tv2 = (TextView) view.findViewById(R.id.number);
holder.ch = (CheckBox) view.findViewById(R.id.checkbox1);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.tv1.setText(contactItem.getConatct_name());
holder.tv2.setText(contactItem.getNumber());
return view;
}
}
in ContactItem you need to maintain Checked Status. and change getView as follows,
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder=null;
View view = convertView;
ContactItem contactItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
view = mInflater.inflate(R.layout.contact_list, null);
holder = new ViewHolder();
holder.tv1 = (TextView) view.findViewById(R.id.name);
holder.tv2 = (TextView) view.findViewById(R.id.number);
holder.ch = (CheckBox) view.findViewById(R.id.checkbox1);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.tv1.setText(contactItem.getConatct_name());
holder.tv2.setText(contactItem.getNumber());
holder.ch.setOnCheckedChangeListener(null);
holder.ch.setChecked(contactItem.getCheckedStatus());
holder.ch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
contactItem.setCheckedStatus(isChecked);
}
});
return view;
}
you have to add another variable in ContactItem like below:
private boolean isSelected;
generate getter and setter method of this variable after that in your adapter :
public class contactAdpter extends ArrayAdapter {
Context context;
List<ContactItem> list;
public contactAdpter(Context context, int resource, List<ContactItem> items) {
super(context, resource,items);
this.context = context;
this.list = items;
}
static class ViewHolder {
ImageView imageview;
TextView tv1;
TextView tv2;
CheckBox ch;
}
#Override
public int getCount() {
return list.size();
}
#Override
public int getPosition(ContactItem item) {
return super.getPosition(item);
}
#Override
public long getItemId(int id) {
return id;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder=null;
View view = convertView;
ContactItem contactItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
view = mInflater.inflate(R.layout.contact_list, null);
holder = new ViewHolder();
holder.tv1 = (TextView) view.findViewById(R.id.name);
holder.tv2 = (TextView) view.findViewById(R.id.number);
holder.ch = (CheckBox) view.findViewById(R.id.checkbox1);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.tv1.setText(contactItem.getConatct_name());
holder.tv2.setText(contactItem.getNumber());
if(contactItem.isSelected){
holder.ch.isChecked(true);
} else {
holder.ch.isChecked(false);
}
holder.ch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(contactItem.isSelected){
holder.ch.isChecked(false);
contactItem.setChecked(false);
} else {
holder.ch.isChecked(true);
contactItem.setChecked(true);
}
notifyDatasetChanged();
}
});
return view;
}
}

Categories

Resources