Android setting Condition in onCheckedChanged - android

I am displaying images from the gallery to my custom grid view with checkbox.
I have to select 6 images only.
I have the following code
public class MultiPhotoSelectActivity extends BaseActivity {
private ArrayList<String> imageUrls;
private DisplayImageOptions options;
private ImageAdapter imageAdapter;
CheckBox mCheckBox;
int pos;
ArrayList<String> selectedItems;
ArrayList<String> selectedimgs = new ArrayList<String>();
RelativeLayout rl_gallery_row,rl_gallery_async;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ac_image_grid);
//Bundle bundle = getIntent().getExtras();
//imageUrls = bundle.getStringArray(Extra.IMAGES);
rl_gallery_async = (RelativeLayout) findViewById(R.id.RelativeLayout_galleryas);
final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
Cursor imagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
null, orderBy + " DESC");
this.imageUrls = new ArrayList<String>();
for (int i = 0; i < imagecursor.getCount(); i++) {
imagecursor.moveToPosition(i);
int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
imageUrls.add(imagecursor.getString(dataColumnIndex));
System.out.println("=====> Array path => "+imageUrls.get(i));
}
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.stub_image)
.showImageForEmptyUri(R.drawable.image_for_empty_url)
.cacheInMemory()
.cacheOnDisc()
.build();
imageAdapter = new ImageAdapter(this, imageUrls);
GridView gridView = (GridView) findViewById(R.id.gridview);
gridView.setAdapter(imageAdapter);
/*gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
startImageGalleryActivity(position);
}
});*/
}
#Override
protected void onStop() {
imageLoader.stop();
super.onStop();
}
public void btnChoosePhotosClick(View v){
selectedItems = imageAdapter.getCheckedItems();
Toast.makeText(MultiPhotoSelectActivity.this, "Total photos selected: "+selectedItems.size(), Toast.LENGTH_SHORT).show();
Log.d(MultiPhotoSelectActivity.class.getSimpleName(), "Selected Items: " + selectedItems.toString());
}
public class ImageAdapter extends BaseAdapter {
ArrayList<String> mList;
LayoutInflater mInflater;
Context mContext;
SparseBooleanArray mSparseBooleanArray;
public ImageAdapter(Context context, ArrayList<String> imageList) {
// TODO Auto-generated constructor stub
mContext = context;
mInflater = LayoutInflater.from(mContext);
mSparseBooleanArray = new SparseBooleanArray();
mList = new ArrayList<String>();
this.mList = imageList;
}
public ArrayList<String> getCheckedItems() {
ArrayList<String> mTempArry = new ArrayList<String>();
for(int i=0;i<mList.size();i++) {
if(mSparseBooleanArray.get(i)) {
mTempArry.add(mList.get(i));
}
}
return mTempArry;
}
#Override
public int getCount() {
return imageUrls.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
pos = position;
if(convertView == null) {
convertView = mInflater.inflate(R.layout.row_multiphoto_item, null);
}
mCheckBox = (CheckBox) convertView.findViewById(R.id.checkBox1);
final ImageView imageView = (ImageView) convertView.findViewById(R.id.imageView1);
rl_gallery_row = (RelativeLayout) findViewById(R.id.Relativelayout_gallery_row);
imageLoader.displayImage("file://"+imageUrls.get(position), imageView, options, new SimpleImageLoadingListener() {
#Override
public void onLoadingComplete(Bitmap loadedImage) {
Animation anim = AnimationUtils.loadAnimation(MultiPhotoSelectActivity.this, R.anim.fade_in);
imageView.setAnimation(anim);
anim.start();
}
});
mCheckBox.setTag(position);
//mCheckBox.setId(position);
mCheckBox.setChecked(mSparseBooleanArray.get(position));
mCheckBox.setOnCheckedChangeListener(mCheckedChangeListener);
//mCheckBox.setId(position);
//holder.imageview.setId(position);
return convertView;
}
OnCheckedChangeListener mCheckedChangeListener = new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
mSparseBooleanArray.put((Integer) buttonView.getTag(), isChecked);
selectedItems = imageAdapter.getCheckedItems();
if(selectedItems.size() > 5 )
{
mCheckBox.setEnabled(false); // disable checkbox
}
}
};
}
}
Now i am not able to uncheck the checkbox automatically when the limit is crossed..
Please help..

I think your condition is not satisfied for unchecking the check box, try to put a toast inside your condition

Related

check size of image on checkbox click

I have a GridView which shows all the images from phone. I'm able to select multiple images and save the selected images to arraylist. I want to restrict the size of the selected images to 1MB. For that I want to check the size of every image while selecting. If the size of clicked image is less than 1MB then it will get selected, otherwise not. Is there any way to do that?
Activity
public class CustomGalleryActivity extends AppCompatActivity implements View.OnClickListener {
private static Button selectImages;
private static GridView galleryImagesGridView;
private static ArrayList<String> galleryImageUrls;
private static GridViewAdapter imagesAdapter;
int file_size;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.customgallery_activity);
initViews();
setListeners();
fetchGalleryImages();
setUpGridView();
}
//Init all views
private void initViews() {
selectImages = (Button) findViewById(R.id.selectImagesBtn);
galleryImagesGridView = (GridView) findViewById(R.id.galleryImagesGridView);
}
//fetch all images from gallery
private void fetchGalleryImages() {
final String[] columns = {MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID};//get all columns of type images
final String orderBy = MediaStore.Images.Media.DATE_TAKEN;//order data by date
Cursor imagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
null, orderBy + " DESC");//get all data in Cursor by sorting in DESC order
galleryImageUrls = new ArrayList<String>();//Init array
//Loop to cursor count
for (int i = 0; i < imagecursor.getCount(); i++) {
imagecursor.moveToPosition(i);
int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);//get column index
galleryImageUrls.add(imagecursor.getString(dataColumnIndex));//get Image from column index
System.out.println("Array path" + galleryImageUrls.get(i));
}
}
//Set Up GridView method
private void setUpGridView() {
imagesAdapter = new GridViewAdapter(CustomGalleryActivity.this, galleryImageUrls);
galleryImagesGridView.setAdapter(imagesAdapter);
}
//Set Listeners method
private void setListeners() {
selectImages.setOnClickListener(this);
}
//Show hide select button if images are selected or deselected
public void showSelectButton() {
ArrayList<String> selectedItems = imagesAdapter.getCheckedItems();
if (selectedItems.size() > 0) {
selectImages.setText(selectedItems.size() + " - Images Selected");
selectImages.setVisibility(View.VISIBLE);
} else
selectImages.setVisibility(View.GONE);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.selectImagesBtn:
//When button is clicked then fill array with selected images
ArrayList<String> selectedItems = imagesAdapter.getCheckedItems();
//Send back result to MainActivity with selected images
Intent intent = new Intent();
intent.putExtra(UploadActivity.CustomGalleryIntentKey, selectedItems.toString());//Convert Array into string to pass data
setResult(RESULT_OK, intent);//Set result OK
finish();//finish activity
break;
}
}
}
public class GridViewAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> imageUrls;
private SparseBooleanArray mSparseBooleanArray;
public GridViewAdapter(Context context, ArrayList<String> imageUrls) {
this.context = context;
this.imageUrls = imageUrls;
mSparseBooleanArray = new SparseBooleanArray();
}
//Method to return selected Images
public ArrayList<String> getCheckedItems() {
ArrayList<String> mTempArry = new ArrayList<String>();
for (int i = 0; i < imageUrls.size(); i++) {
if (mSparseBooleanArray.get(i)) {
mTempArry.add(imageUrls.get(i));
}
}
return mTempArry;
}
#Override
public int getCount() {
return imageUrls.size();
//return 10;
}
#Override
public Object getItem(int i) {
return imageUrls.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null)
view = inflater.inflate(R.layout.customgridview_item, viewGroup, false);//Inflate layout
CheckBox mCheckBox = (CheckBox) view.findViewById(R.id.selectCheckBox);
final ImageView imageView = (ImageView) view.findViewById(R.id.galleryImageView);
Picasso.with(context).load("file://" + imageUrls.get(position)).placeholder(R.drawable.placeholder).into(imageView);
mCheckBox.setTag(position);//Set Tag for CheckBox
mCheckBox.setChecked(mSparseBooleanArray.get(position));
mCheckBox.setOnCheckedChangeListener(mCheckedChangeListener);
return view;
}
CompoundButton.OnCheckedChangeListener mCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
System.out.println("sammy_position "+buttonView.getTag());
File f = new File(imageUrls.get((Integer) buttonView.getTag()));
int file_size = Integer.parseInt(String.valueOf(f.length() / (1024*1024)));
// Filtering the image size
if(file_size<1){
mSparseBooleanArray.put((Integer) buttonView.getTag(), isChecked);//Insert selected checkbox value inside boolean array
((CustomGalleryActivity) context).showSelectButton();//call custom gallery activity method
}else{
buttonView.setChecked(false);
Toast.makeText(context, "Select image of size 1MB or less", Toast.LENGTH_SHORT).show();
}
}
};
}
public void calculateImageSize(int imageId){
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
imageId);
Bitmap bitmap = bitmapOrg;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageInByte = stream.toByteArray();
long lengthbmp = imageInByte.length;
double sizeInKB=(lengthbmp/1024);
double sizeInMB=(lengthbmp/(1024*1024));
Log.d("TAG","Size "+sizeInKB+"KB");
Log.d("TAG","Size "+sizeInMB+"MB");
}
Replace Adapter With this
import android.content.Context;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import java.util.ArrayList;
public class GridViewAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> imageUrls;
private SparseBooleanArray mSparseBooleanArray;
private boolean isCustomGalleryActivity;
public GridViewAdapter(Context context, ArrayList<String> imageUrls, boolean isCustomGalleryActivity) {
this.context = context;
this.imageUrls = imageUrls;
this.isCustomGalleryActivity = isCustomGalleryActivity;
mSparseBooleanArray = new SparseBooleanArray();
}
//Method to return selected Images
public ArrayList<String> getCheckedItems() {
ArrayList<String> mTempArry = new ArrayList<String>();
for (int i = 0; i < imageUrls.size(); i++) {
if (mSparseBooleanArray.get(i)) {
mTempArry.add(imageUrls.get(i));
}
}
return mTempArry;
}
#Override
public int getCount() {
return imageUrls.size();
//return 10;
}
#Override
public Object getItem(int i) {
return imageUrls.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null)
view = inflater.inflate(R.layout.customgridview_item, viewGroup, false);//Inflate layout
CheckBox mCheckBox = (CheckBox) view.findViewById(R.id.selectCheckBox);
final ImageView imageView = (ImageView) view.findViewById(R.id.galleryImageView);
//If Context is MainActivity then hide checkbox
if (!isCustomGalleryActivity)
mCheckBox.setVisibility(View.GONE);
Picasso.with(context).load("file://" + imageUrls.get(position)).placeholder(R.drawable.placeholder).into(imageView);
mCheckBox.setTag("file://" + imageUrls.get(position));
mCheckBox.setId(position);//Set Tag for CheckBox
mCheckBox.setChecked(mSparseBooleanArray.get(position));
mCheckBox.setOnCheckedChangeListener(mCheckedChangeListener);
return view;
}
CompoundButton.OnCheckedChangeListener mCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mSparseBooleanArray.put((Integer) buttonView.getId(), isChecked);//Insert selected checkbox value inside boolean array
String imagePath = (String) buttonView.getTag();
((CustomGalleryActivity) context).showSelectButton();//call custom gallery activity method
}
};
}
Use this function to find out the size in kb & MB

Get checked items id from custom listview and pass them to new activity android

I'm developing an android app which has a custom listview with a checkbox. I want to pass all the checked items from one activity to another. how should I pass them? and where should I manage the checkbox (to get all the checked items) in the custom adapter or the activity?
Note: I retrieve all the data from my server using json response.
Here's my Model :
public class Groups {
public String name;
public boolean selected= false;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public Groups() {
}
}
My Adapter:
public class AdapterMainActivity extends BaseAdapter{
Activity activity;
private LayoutInflater inflater;
List<Groups> groupsList;
public AdapterMainActivity(Activity activity, List<Groups> groupses) {
this.activity = activity;
this.groupsList = groupses;
}
#Override
public int getCount() {
return groupsList.size();
}
#Override
public Object getItem(int position) {
return groupsList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (inflater == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.custom_list, null);
TextView name = (TextView) convertView.findViewById(R.id.textViewName);
final CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
final Groups groups = groupsList.get(position);
name.setText(groupsList.get(position).getName());
checkBox.setChecked(groups.selected);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
groups.selected = isChecked;
MainActivity.getInstance().updateArrayList(groupsList);
}
});
}
return convertView;
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
ListView listViewGroups;
Button buttonSentToActivity;
List<Groups> groupsList;
List<Groups> resultGroupList;
ArrayList<Boolean> areChecked;
List<String> finalArray;
private AdapterMainActivity adapterMainActivity;
static MainActivity yourActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
yourActivity = this;
groupsList= new ArrayList<Groups>();
resultGroupList= new ArrayList<Groups>();
ReadGroup(37);
adapterMainActivity = new AdapterMainActivity(this, groupsList);
listViewGroups = (ListView) findViewById(R.id.listViewGroups);
listViewGroups.setAdapter(adapterMainActivity);
buttonSentToActivity = (Button) findViewById(R.id.buttonSendTo2Activity);
buttonSentToActivity.setOnClickListener(buttonSentToActivityListener);
Log.e("Group list size ", String.valueOf(groupsList.size()));
finalArray = new ArrayList<>();
for (int i = 0; i < resultGroupList.size(); i++) {
if (resultGroupList.get(i).selected) {
finalArray.add(resultGroupList.get(i).getName());
Log.e("final array size", String.valueOf(finalArray.size()));
}
}
}
public void ReadGroup(long cid) {
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response.toString());
JSONArray readArray = jsonObject.getJSONArray("groups");
for (int i = 0; i < readArray.length(); i++) {
Log.e("i is: ", String.valueOf(i));
JSONObject jssonRow = readArray.getJSONObject(i);
String groupName = jssonRow.getString("name");
Groups groups = new Groups();
groups.setName(groupName);
Log.e("NAME is: ", groupName);
groupsList.add(groups);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapterMainActivity.notifyDataSetChanged();
}
};
Log.e("Client id is: ", String.valueOf(cid));
ReadGroupRequesr readGroupRequest = new ReadGroupRequesr(cid, responseListener);
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
queue.add(readGroupRequest);
Log.e("out of the loop", "");
}
public static MainActivity getInstance() {
return yourActivity;
}
public void updateArrayList(List<Groups> arrayList) {
this.resultGroupList = arrayList;
}
View.OnClickListener buttonSentToActivityListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
//Bundle b= new Bundle();
//b.putStringArrayList("arrayList", (ArrayList<String>) finalArray);
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putStringArrayListExtra("arrayList", (ArrayList<String>) finalArray);
//intent.putExtras(b);
Log.e("final array size", String.valueOf(finalArray.size()));
startActivity(intent);
}
};
}
At the very first, manage your checkboxes :
In your activity class add a boolean array or arraylist having size same as your list array size and initialize it with all value as false initially :
String[] titlesArray;
ArrayList<Boolean> arrChecked;
// initialize arrChecked boolean array and add checkbox value as false initially for each item of listview
arrChecked = new ArrayList<Boolean>();
for (int i = 0; i < titles.size(); i++) {
arrChecked.add(false);
}
Now replace your adapter class with this :
class VivzAdapter extends ArrayAdapter<String> implements OnCheckedChangeListener {
Context context;
int[] images;
String[] titlesArray, descrptionArray;
List<Integer> positions = new ArrayList<Integer>();
ArrayList<Boolean> arrChecked;
VivzAdapter(Context context, String[] titles, int[] images, String[] description, ArrayList<Boolean> arrChecked) {
super(context, R.layout.single_row, R.id.textView1, titles);
this.context = context;
this.images = images;
this.titlesArray = titles;
this.descrptionArray = description;
this.arrChecked = arrChecked;
}
class MyViewHolder {
ImageView myImage;
TextView myTitle;
TextView myDescription;
CheckBox box;
MyViewHolder(View v) {
myImage = (ImageView) v.findViewById(R.id.imageView1);
myTitle = (TextView) v.findViewById(R.id.textView1);
myDescription = (TextView) v.findViewById(R.id.textView2);
box = (CheckBox) v.findViewById(R.id.checkBox1);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
MyViewHolder holder = null;
if (row == null) {
// 1.Âștime
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//row contem RelativeLayout(root) em single_row.xml
row = inflater.inflate(R.layout.single_row, parent, false);
holder = new MyViewHolder(row);
row.setTag(holder);
//Log.d("VIVZ", "Creating a new Row");
} else {
//reciclamos aqui, qeremos usar antigo objecto holder
holder = (MyViewHolder) row.getTag();
//Log.d("VIVZ", "Recycling stuff");
}
holder.myImage.setImageResource(images[position]);
holder.myTitle.setText(titlesArray[position]);
holder.myDescription.setText(descrptionArray[position]);
//set position as id
holder.box.setId(position);
//set onClickListener of checkbox rather than onCheckedChangeListener
holder.box.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int id = v.getId();
if (arrChecked.get(id)) {
//if checked, make it unchecked
arrChecked.set(id, false);
} else {
//if unchecked, make it checked
arrChecked.set(id, true);
}
}
});
//set the value of each checkbox from arrChecked boolean array
holder.box.setChecked(arrChecked.get(position));
return row;
}
}
After that, implement click listener of send button say btnSend button (I am considering that you are sending your data from one activity to another activity on click of send button) :
btnSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<String> arrTempList = new ArrayList();
for(int i=0; i<titles.size(); i++){
if(arrChecked.get(i) == true){
arrTempList.add(titles[i]);
}
}
// here you can send your arrTempList which is having checked items only
}
});
Here's the solution for this Question:
My adapter:
public class ChooseContactsAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
public ArrayList<Contacts> contactsList;
public CheckBox checkBoxAdapter;
public ChooseContactsAdapter(Activity activity, ArrayList<Contacts> group) {
this.activity = activity;
this.contactsList = group;
}
#Override
public int getCount() {
return contactsList.size();
}
#Override
public Object getItem(int position) {
return contactsList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.custom_choose_contacts_sms,
null);
final TextView fNAme = (TextView) convertView.findViewById(R.id.textViewCustomSMSSelectContactFName);
TextView LName = (TextView) convertView.findViewById(R.id.textViewCustomSMSSelectContactLName);
checkBoxAdapter = (CheckBox) convertView.findViewById(R.id.checkBoxSelectContact);
checkBoxAdapter.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
CheckBox cb = (CheckBox) view;
Contacts contacts = (Contacts) cb.getTag();
contacts.setSelected(cb.isChecked());
Toast.makeText(activity.getApplicationContext(),
"Clicked on Checkbox: " + cb.getText() +
" is " + cb.isChecked(),
Toast.LENGTH_LONG).show();
}
});
final Contacts contacts = contactsList.get(position);
fNAme.setText(contacts.getContactFName());
LName.setText(contacts.getContactLName());
checkBoxAdapter.setChecked(contacts.isSelected());
checkBoxAdapter.setTag(contacts);
}
return convertView;
}
}
In my activity I have button to go from 1 activity to the 2 activity:
private View.OnClickListener buttonSubmitGroupListener =new View.OnClickListener() {
#Override
public void onClick(View view) {
List <Integer> contactsIDArray= new ArrayList<Integer>();
List<Contacts> arrayOfContacts= chooseContactsAdapter.contactsList;
for(int i=0; i< arrayOfContacts.size(); i++){
Contacts contacts= arrayOfContacts.get(i);
if(contacts.isSelected()==true){
contactsIDArray.add(contacts.getContactID());
}
}
for (int i = 0; i < contactsIDArray.size(); i++) {
Log.e("Id Array size ", String.valueOf(contactsIDArray.size()));
Log.e("Selected id ", String.valueOf(contactsIDArray.get(i)));
}
intent = new Intent(getApplicationContext(), SendSMSActivity.class);
Bundle b = new Bundle();
b.putIntegerArrayList("checkedContacts", (ArrayList<Integer>) contactsIDArray);
intent.putExtras(b);
startActivity(intent);
}
};
Second Activity add this code:
Bundle b = getIntent().getExtras();
List<Integer> result = new ArrayList<Integer>();
result = b.getIntegerArrayList("checkedContacts");

Deleting listview item from database

I am deleting the title 2 list item item
But the last title gets deleted that is the title 8 gets deleted
When I then go back to the previous screen and reopen the list. The correct that is the 2nd item title 2 had been deleted.
Here is the DataAdapter
public class DataAdapter extends BaseAdapter {
String a[];
Context ctx;
View.OnClickListener onClickListener;
MyDBHandler dbHelper;
AlertDialog alertDialog;
ArrayList<Calendars> arrayList;
public DataAdapter(Context reminderList, ArrayList<Calendars> arrayList, MyDBHandler dbHelper) {
this.ctx = reminderList;
this.arrayList = arrayList;
this.dbHelper = dbHelper;
}
public void Swap(ArrayList<Calendars> arrayList) {
this.arrayList.clear();
this.arrayList.addAll(arrayList);
this.notifyDataSetChanged();
Log.e("arraylist", arrayList.toString());
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflate = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflate.inflate(R.layout.activity_view_record, parent, false);
final ViewHolder holder = new ViewHolder();
holder.dateTextView = (TextView) convertView.findViewById(R.id.datelist);
holder.timeTextView = (TextView) convertView.findViewById(R.id.timelist);
holder.titleTextView = (TextView) convertView.findViewById(R.id.titlelist);
holder.idTextview = (TextView) convertView.findViewById(R.id.idlist);
holder.deleteButton = (Button) convertView.findViewById(R.id.deletelist);
holder.dateTextView.setText(arrayList.get(position).get_reminderdate());
holder.timeTextView.setText(arrayList.get(position).get_remindertime());
holder.titleTextView.setText(arrayList.get(position).get_remindertitle());
holder.idTextview.setText(arrayList.get(position).get_id() + "");
holder.deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder adb = new AlertDialog.Builder(v.getRootView().getContext());
adb.setTitle("Delete");
adb.setMessage("Are you sure you want to delete this reminder?");
//final int positionToRemove = view.getId();
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dbHelper.remove(arrayList.get(position).get_id());
Log.e("position", position + "");
arrayList.remove(position);
arrayList = dbHelper.databaseToArrayList();
notifyDataSetInvalidated();
notifyDataSetChanged();
//Swap(dbHelper.databaseToArrayList());
}
});
adb.show();
}
});
}
return convertView;
}
class ViewHolder {
TextView titleTextView, dateTextView, timeTextView, idTextview;
Button deleteButton;
}
}
Here is the ListActivity
public class ReminderList extends ActionBarActivity {
Calendars calendars;
Button deleteButton;
private MyDBHandler dbHelper;
private ListView listView;
private ArrayList<Calendars> arrayList;
private SimpleCursorAdapter adapter;
int pos;
DataAdapter dataAdapter;
final String[] from = new String[]{MyDBHandler.COLUMN_REMINDER_TITLE,
MyDBHandler.COLUMN_REMINDER_DATE, MyDBHandler.COLUMN_REMINDER_TIME, MyDBHandler.COLUMN_ID,
MyDBHandler.COLUMN_REMINDER_DESCRIPTION, MyDBHandler.COLUMN_REMINDER_SNOOZE, MyDBHandler.COLUMN_REMINDER_REPEAT, MyDBHandler.COLUMN_ID};
final int[] to = new int[]{R.id.titlelist, R.id.datelist, R.id.timelist, R.id.idlist,
R.id.descriptionlist, R.id.snoozelist, R.id.repeatlist, R.id.deletelist};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reminder_list);
deleteButton = (Button) findViewById(R.id.deletelist);
// adapter=new DataAdapter(ReminderList.this,from);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onStart() {
arrayList = new ArrayList<Calendars>();
dbHelper = new MyDBHandler(this);
Cursor cursor = dbHelper.fetch();
arrayList = dbHelper.databaseToArrayList();
listView = (ListView) findViewById(R.id.list_view);
listView.setEmptyView(findViewById(R.id.empty));
dataAdapter = new DataAdapter(this, arrayList, dbHelper);
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long viewId) {
String title = arrayList.get(position).get_remindertitle();
Log.d("title", title);
String date = arrayList.get(position).get_reminderdate();
String time = arrayList.get(position).get_remindertime();
String id = arrayList.get(position).get_id() + "";
String description = arrayList.get(position).get_reminderdescription();
String snooze = arrayList.get(position).get_remindersnooze();
String repeat = arrayList.get(position).get_reminderrepeat();
Intent modify_intent = new Intent(getApplicationContext(), AlarmActivity.class);
modify_intent.putExtra("id", id);
modify_intent.putExtra("title", title);
modify_intent.putExtra("time", time);
modify_intent.putExtra("date", date);
modify_intent.putExtra("description", description);
modify_intent.putExtra("snooze", snooze);
modify_intent.putExtra("repeat", repeat);
startActivity(modify_intent);
dataAdapter.notifyDataSetChanged();
listView.invalidateViews();
}
});
super.onStart();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: {
NavUtils.navigateUpFromSameTask(this);
return true;
}
case R.id.add_record: {
Intent add_mem = new Intent(this, AlarmActivity.class);
startActivity(add_mem);
}
default:
return super.onOptionsItemSelected(item);
}
}
}
DatabasetoArraylist function
public ArrayList<Calendars> databaseToArrayList() {
ArrayList<Calendars> arrayList = new ArrayList();
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_REMINDER;
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while (!c.isAfterLast()) {
if (c.getString(c.getColumnIndex("_reminderdate")) != null) {
Calendars calendars = new Calendars();
calendars.set_id(c.getInt(c.getColumnIndex(COLUMN_ID)));
calendars.set_reminderdate(c.getString(c.getColumnIndex(COLUMN_REMINDER_DATE)));
calendars.set_remindertime(c.getString(c.getColumnIndex(COLUMN_REMINDER_TIME)));
calendars.set_remindertitle(c.getString(c.getColumnIndex(COLUMN_REMINDER_TITLE)));
calendars.set_reminderdescription(c.getString(c.getColumnIndex(COLUMN_REMINDER_DESCRIPTION)));
calendars.set_reminderrepeat(c.getString(c.getColumnIndex(COLUMN_REMINDER_REPEAT)));
calendars.set_remindersnooze(c.getString(c.getColumnIndex(COLUMN_REMINDER_SNOOZE)));
arrayList.add(calendars);
}
c.moveToNext();
}
c.close();
db.close();
return arrayList;
}
Change your getView() method of adapter by below code:
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
final Calendars calendars = arrayList.get(position);
if (convertView == null)
{
LayoutInflater inflate = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflate.inflate(R.layout.activity_view_record, parent, false);
holder = new ViewHolder();
holder.dateTextView = (TextView) convertView.findViewById(R.id.datelist);
holder.timeTextView = (TextView) convertView.findViewById(R.id.timelist);
holder.titleTextView = (TextView) convertView.findViewById(R.id.titlelist);
holder.idTextview = (TextView) convertView.findViewById(R.id.idlist);
holder.deleteButton = (Button) convertView.findViewById(R.id.deletelist);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.dateTextView.setText(calendars.get_reminderdate());
holder.timeTextView.setText(calendars.get_remindertime());
holder.titleTextView.setText(calendars.get_remindertitle());
holder.idTextview.setText(calendars.get_id() + "");
holder.deleteButton.setTag(calendars);
holder.deleteButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
AlertDialog.Builder adb = new AlertDialog.Builder(v.getRootView().getContext());
adb.setTitle("Delete");
adb.setMessage("Are you sure you want to delete this reminder?");
//final int positionToRemove = view.getId();
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
final selectedCalendar = (Calendars) holder.deleteButton.getTag();
dbHelper.remove(selectedCalendar.get_id());
arrayList = dbHelper.databaseToArrayList();
notifyDataSetInvalidated();
notifyDataSetChanged();
//Swap(dbHelper.databaseToArrayList());
}
});
adb.show();
}
});
}
return convertView;
}

i cannot set select all checkbox to listview here is my code

Code for custome adapter
public class CustomAdapter extends BaseAdapter{
private Context context;
private ArrayList<String> name;
private ArrayList<String> id;
private ArrayList<String> group;
boolean checkBoxState;
public CustomAdapter( Context c,ArrayList<String> Cid, ArrayList<String> Cname,ArrayList<String> Cgroup) {
this.name = Cname;
this.id=Cid;
this.group = Cgroup;
MsgActivity msg=new MsgActivity();
this.context = c;
}
#Override
public int getCount() {
return id.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View Child, ViewGroup parent) {
Holder mholder;
LayoutInflater layoutInflater;
if(Child==null) {
layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
Child = layoutInflater.inflate(R.layout.listview, null);
mholder = new Holder();
mholder.txt_name = (TextView) Child.findViewById(R.id.tvlist_name);
mholder.txt_Grp = (TextView) Child.findViewById(R.id.tvlist_group);
mholder.txt_id = (TextView) Child.findViewById(R.id.tvlist_id);
mholder.chk_box=(CheckBox) Child.findViewById(R.id.cbList_hook);
Child.setTag(mholder);
}
else
{
mholder=(Holder) Child.getTag();
}
mholder.txt_name.setText(name.get(position));
mholder.txt_Grp.setText(group.get(position));
mholder.txt_id.setText(id.get(position));
mholder.chk_box.setChecked(true);
return Child;
}
public class Holder {
TextView txt_id;
TextView txt_name;
TextView txt_Grp;
CheckBox chk_box;
}
}
code for display activity
public class MsgActivity extends AppCompatActivity implements OnItemSelectedListener {
EditText tx1;
TextView tv;
Button b1,b2,b3;
Spinner sp;
ListView lv;
String dat3;
SQLiteDatabase dh;
DbHelper mhelper;
public Integer m=null;
AddgrpActivity addgrp;
public CheckBox cb;
private ArrayList<String> userId = new ArrayList<>();
private ArrayList<String> user_name = new ArrayList<>();
private ArrayList<String> user_num = new ArrayList<>();
ArrayList<String> groups = new ArrayList<>();
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
dat3=sp.getSelectedItem().toString();
Toast.makeText(getApplicationContext(),dat3,Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_msg);
tx1 = (EditText) findViewById(R.id.editText);
b1 = (Button) findViewById(R.id.button2_add_msg);
b2 = (Button) findViewById(R.id.button_snd);
sp = (Spinner) findViewById(R.id.spinner);
lv = (ListView) findViewById(R.id.listView);
sp.setOnItemSelectedListener(this);
mhelper = new DbHelper(this);
cb=(CheckBox)findViewById(R.id.checkBox_1);
tv=(TextView)findViewById(R.id.textView);
groups = addgrp.Addall();
groups.add("all");
ArrayAdapter<String> grps = new ArrayAdapter(this, android.R.layout.simple_spinner_item, groups);
grps.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(grps);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
userId.clear();
user_name.clear();
user_num.clear();
dh = mhelper.getReadableDatabase();
Cursor mCursor;
if (dat3 == "all") {
mCursor = dh.rawQuery("SELECT * FROM "
+ DbHelper.TABLE_NAME, null);
if (mCursor.moveToFirst()) {
do {
userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
user_name.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_NAME)));
user_num.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_GRP)));
} while (mCursor.moveToNext());
CustomAdapter cst = new CustomAdapter(MsgActivity.this, userId, user_name, user_num);
//ArrayAdapter cst = new ArrayAdapter(MsgActivity.this, android.R.layout.simple_list_item_multiple_choice, user_name);
lv.setAdapter(cst);
}
} else {
mCursor = dh.rawQuery("select * from " + DbHelper.TABLE_NAME + " where " + DbHelper.KEY_GRP + " = ?", new String[]{dat3});
if (mCursor.moveToFirst()) {
do {
userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
user_name.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_NAME)));
user_num.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_GRP)));
lv.setChoiceMode(lv.CHOICE_MODE_MULTIPLE_MODAL);
//user_sal.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_SAL)));
} while (mCursor.moveToNext());
}
}
final CustomAdapter cst = new CustomAdapter(MsgActivity.this, userId, user_name, user_num);
// ArrayAdapter cst=new ArrayAdapter(MsgActivity.this,android.R.layout.simple_list_item_multiple_choice,user_name);
//lv.setChoiceMode(lv.CHOICE_MODE_MULTIPLE_MODAL);
lv.setAdapter(cst);
mCursor.close();
}
});
}
public void onBackPressed() {
Intent in = new Intent(MsgActivity.this, MainActivity.class);
startActivity(in);
}
}

checkbox in listview for multiple selection of contacts

I had tried to to put checkbox in listview through layout inflator and I got success but the problem is when I select the multiple contacts there is no problem but when I deselect it & when I scroll down & then go back to that deselected checkbox its get automatically selected...
public class Contactlist_selfActivity extends ListActivity {
/** Called when the activity is first created. */
private ArrayList<contact> contact_list = null;
private ProgressDialog mProgressDialog = null;
private contactAdapter mContactAdapter = null;
private Runnable mViewcontacts = null;
private SparseBooleanArray mSelectedContacts = new SparseBooleanArray();
private ArrayList<contact> items;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
contact_list = new ArrayList<contact>();
this.mContactAdapter = new contactAdapter(this, R.layout.listview,
contact_list);
ListView lv = getListView();
setListAdapter(this.mContactAdapter);
lv.setItemsCanFocus(false);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
// }
mViewcontacts = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
getContacts();
}
};
Thread thread = new Thread(null, mViewcontacts, "ContactReadBackground");
thread.start();
mProgressDialog = ProgressDialog.show(Contactlist_selfActivity.this,
"Please Wait...", "Retriving Contacts...", true);
}
#SuppressWarnings("unused")
private void getContacts() {
// TODO Auto-generated method stub
try {
String[] projection = new String[] {
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER,
ContactsContract.Contacts._ID };
Cursor mCursor = managedQuery(
ContactsContract.Contacts.CONTENT_URI, projection,
ContactsContract.Contacts.HAS_PHONE_NUMBER + "=?",
new String[] { "1" },
ContactsContract.Contacts.DISPLAY_NAME);
while (mCursor.moveToNext()) {
contact contact = new contact();
String contactId = mCursor.getString(mCursor
.getColumnIndex(ContactsContract.Contacts._ID));
contact.setContactName(mCursor.getString(mCursor
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
contact_list.add(contact);
}
mCursor.close();
runOnUiThread(returnRes);
} catch (Exception e) {
// TODO: handle exception
Log.d("getContacts", e.getMessage());
}
}
public class contactAdapter extends ArrayAdapter<contact> {
private int[] isChecked;
public contactAdapter(Context context, int textViewResourceId,
ArrayList<contact> items1) {
super(context, textViewResourceId, items1);
items = items1;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
final int position_clicked = 0;
// Log.i("asd", "getView :" + getItem(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.listview, parent, false);
}
contact contacts = items.get(position);
isChecked = new int[items.size()];
if (contacts != null) {
final CheckBox nameCheckBox = (CheckBox) convertView
.findViewById(R.id.checkBox);
nameCheckBox.setChecked(mSelectedContacts.get(position));
for (int i = 0; i < isChecked.length; i++) {
}
if (nameCheckBox != null) {
nameCheckBox.setText(contacts.getContactName());
}
nameCheckBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
isChecked[position_clicked] = position;
Log.d("position", String.valueOf(position));
}
});
}
return convertView;
}
}
private Runnable returnRes = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
mContactAdapter.notifyDataSetChanged();
}
};
}
i found the answer....
i had just taken a new variable in contact class...
public class PlanetsActivity extends Activity {
private ListView mainListView;
private Contact[] contact_read;
private Cursor mCursor;
private ArrayAdapter<Contact> listAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Find the ListView resource.
mainListView = (ListView) findViewById(R.id.mainListView);
mainListView
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View item,
int position, long id) {
Contact planet = listAdapter.getItem(position);
planet.toggleChecked();
ContactViewHolder viewHolder = (ContactViewHolder) item
.getTag();
viewHolder.getCheckBox().setChecked(planet.isChecked());
}
});
// Throw Query and fetch the contacts.
String[] projection = new String[] { Contacts.HAS_PHONE_NUMBER,
Contacts._ID, Contacts.DISPLAY_NAME };
mCursor = managedQuery(Contacts.CONTENT_URI, projection,
Contacts.HAS_PHONE_NUMBER + "=?", new String[] { "1" },
Contacts.DISPLAY_NAME);
if (mCursor != null) {
mCursor.moveToFirst();
contact_read = new Contact[mCursor.getCount()];
// Add Contacts to the Array
int j = 0;
do {
contact_read[j] = new Contact(mCursor.getString(mCursor
.getColumnIndex(Contacts.DISPLAY_NAME)));
j++;
} while (mCursor.moveToNext());
} else {
System.out.println("Cursor is NULL");
}
// Add Contact Class to the Arraylist
ArrayList<Contact> planetList = new ArrayList<Contact>();
planetList.addAll(Arrays.asList(contact_read));
// Set our custom array adapter as the ListView's adapter.
listAdapter = new ContactArrayAdapter(this, planetList);
mainListView.setAdapter(listAdapter);
}
/** Holds Contact data. */
#SuppressWarnings("unused")
private static class Contact {
private String name = "";
private boolean checked = false;
public Contact() {
}
public Contact(String name) {
this.name = name;
}
public Contact(String name, boolean checked) {
this.name = name;
this.checked = checked;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public String toString() {
return name;
}
public void toggleChecked() {
checked = !checked;
}
}
/** Holds child views for one row. */
#SuppressWarnings("unused")
private static class ContactViewHolder {
private CheckBox checkBox;
private TextView textView;
public ContactViewHolder() {
}
public ContactViewHolder(TextView textView, CheckBox checkBox) {
this.checkBox = checkBox;
this.textView = textView;
}
public CheckBox getCheckBox() {
return checkBox;
}
public void setCheckBox(CheckBox checkBox) {
this.checkBox = checkBox;
}
public TextView getTextView() {
return textView;
}
public void setTextView(TextView textView) {
this.textView = textView;
}
}
/** Custom adapter for displaying an array of Contact objects. */
private static class ContactArrayAdapter extends ArrayAdapter<Contact> {
private LayoutInflater inflater;
public ContactArrayAdapter(Context context, List<Contact> planetList) {
super(context, R.layout.simplerow, R.id.rowTextView, planetList);
// Cache the LayoutInflate to avoid asking for a new one each time.
inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Contact to display
Contact planet = (Contact) this.getItem(position);
System.out.println(String.valueOf(position));
// The child views in each row.
CheckBox checkBox;
TextView textView;
// Create a new row view
if (convertView == null) {
convertView = inflater.inflate(R.layout.simplerow, null);
// Find the child views.
textView = (TextView) convertView
.findViewById(R.id.rowTextView);
checkBox = (CheckBox) convertView.findViewById(R.id.CheckBox01);
// Optimization: Tag the row with it's child views, so we don't
// have to
// call findViewById() later when we reuse the row.
convertView.setTag(new ContactViewHolder(textView, checkBox));
// If CheckBox is toggled, update the Contact it is tagged with.
checkBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Contact contact = (Contact) cb.getTag();
contact.setChecked(cb.isChecked());
}
});
}
// Reuse existing row view
else {
// Because we use a ViewHolder, we avoid having to call
// findViewById().
ContactViewHolder viewHolder = (ContactViewHolder) convertView
.getTag();
checkBox = viewHolder.getCheckBox();
textView = viewHolder.getTextView();
}
// Tag the CheckBox with the Contact it is displaying, so that we
// can
// access the Contact in onClick() when the CheckBox is toggled.
checkBox.setTag(planet);
// Display Contact data
checkBox.setChecked(planet.isChecked());
textView.setText(planet.getName());
return convertView;
}
}
public Object onRetainNonConfigurationInstance() {
return contact_read;
}
}
The cause of this is that when you call nameCheckBox.setChecked() in code OnClickListener() awakes and run its code. I had the same problem an solved in just setting OnClickListener(null) before set a checkbox checked or not.
nameCheckBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
isChecked[position_clicked] = position;
Log.d("position", String.valueOf(position));
}
});
this code in add more one arre list in stores all position and add or remove both said
fast add ,second remove.
and used to list in position your other method

Categories

Resources