I know there are lots of questions related to Custom ListView with CheckBox but still i am getting some problem in retrieving all checked items.
What i am doing is :
Displaying Custom ListView from Database (List of All Sent SMSs).
Allow user to check various list items.
When user presses the Delete Button i want to delete all the checked items (From the database as well as the view portion)
Problem :
When i go to my Activity for the first time and check some items, and delete it, it works fine.
But when i again check some items just after pressing delete button, some items gets checked and some gets unchecked and again some other items are deleted..
I think i am not able to bind id and list item perfectly..
Coding done so far:
row.xml contains
ImageView
TextView
TextView
TextView
CheckBox
In my Activity Class :
Uri uriSms = Uri.parse("content://sms/sent");
Cursor cursor = context.getContentResolver().query(uriSms, null,null,null,null);
String[] from={"address","body"};
int[] to={R.id.contactName,R.id.msgLine};
ssa=new SentSmsAdapter(context,R.layout.inbox_list_item,cursor,from,to,2);
smsList.setAdapter(ssa);
deleteSms.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
ArrayList<Boolean> list=SentSmsAdapter.itemChecked;
Uri path=Uri.parse("content://sms/");
for(int i=0;i<list.size();i++)
{
if(list.get(i))
getContentResolver().delete(path,"_id="+ssa.getItemId(i),null);
}
ssa.notifyDataSetChanged();
}
I have custom SimpleCursorAdapter.
public class SentSmsAdapter extends SimpleCursorAdapter{
Cursor dataCursor;
LayoutInflater mInflater;
Context context;
int layoutType;
ArrayList<String> arrayList;
public static HashMap<String,Long> myList=new HashMap<String,Long>();
public static ArrayList<Boolean> itemChecked = new ArrayList<Boolean>();
public static ArrayList<Long> itemIds=new ArrayList<Long>();
public SentSmsAdapter(Context context, int layout, Cursor dataCursor, String[] from,
int[] to,int type) {
super(context, layout, dataCursor, from, to);
layoutType=type;
this.context=context;
this.dataCursor = dataCursor;
mInflater = LayoutInflater.from(context);
arrayList=new ArrayList<String>();
for (int i = 0; i < this.getCount(); i++) {
itemChecked.add(i, false);
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if(convertView==null)
{
convertView = mInflater.inflate(R.layout.inbox_list_item, null);
holder = new ViewHolder();
holder.checkBox=(CheckBox) convertView.findViewById(R.id.checkMsg);
holder.checkBox.setTag(position);
holder.cName=(TextView)convertView.findViewById(R.id.contactName);
holder.icon=(ImageView)convertView.findViewById(R.id.msgImage);
holder.msg=(TextView)convertView.findViewById(R.id.msgLine);
holder.time=(TextView)convertView.findViewById(R.id.msgTime);
convertView.setTag(holder);
holder.checkBox.setTag(itemChecked.get(position));
}
else
{
holder=(ViewHolder)convertView.getTag();
}
holder.checkBox.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
CheckBox cb = (CheckBox) view.findViewById(R.id.checkMsg);
int pos=Integer.parseInt(holder.checkBox.getTag());
itemChecked.set(position, cb.isChecked());
/*if (cb.isChecked()) {
itemChecked.set(position, true);
Log.i("WhenChecked",Boolean.toString(itemChecked.get(position)));
// do some operations here
}
else if (!cb.isChecked()) {
itemChecked.set(position, false);
Log.i("WhenNotChecked",Boolean.toString(itemChecked.get(position)));
// do some operations here
}
*/
}
});
dataCursor.moveToPosition(position);
String id=Integer.toString(dataCursor.getInt(dataCursor.getColumnIndexOrThrow("_id")));
itemIds.add(Long.parseLong(id));
String msgText=dataCursor.getString(dataCursor.getColumnIndexOrThrow("body"));
holder.msg.setText(msgText);
Long time=dataCursor.getLong(dataCursor.getColumnIndexOrThrow("date"));
holder.time.setText(Long.toString(time));
String address=dataCursor.getString(dataCursor.getColumnIndexOrThrow("address"));
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(address));
Cursor cs= context.getContentResolver().query(uri, new String[]{PhoneLookup.DISPLAY_NAME},null,null,null);
if(cs.getCount()>0)
address=cs.getString(cs.getColumnIndex(PhoneLookup.DISPLAY_NAME));
cs.close();
holder.cName.setText(address);
if(layoutType==1)holder.checkBox.setVisibility(View.GONE);
else
{
holder.checkBox.setVisibility(View.VISIBLE);
}
arrayList.add(id+","+address+","+msgText+","+Long.toString(time));
return convertView;
}
static class ViewHolder
{
ImageView icon;
CheckBox checkBox;
TextView cName;
TextView msg;
TextView time;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return itemIds.get(position);
}
}
Try something like this.
add this code in getView()
holder.checkBox.seTag(position);
holder.checkBox.setOnCheckedChangedListener(this);
implement this outside getView().
public void onCheckedChanged(CompoundButton view,boolean isChecked) {
if(isChecked)
{
itemChecked.add(view.getTag());
}
else
{
if(itemChecked.cantains(view.getTag()))
//remove from itemChecked.
}
}
When deleting delete all the elements from the list whose index is available in itemChecked.
Thanks and N-JOY.
If you use threads when checking, uncheking and deleting your items, they will work properly.
Related
This is my adapter class :
public class CheckboxAdapter extends ArrayAdapter<String> {
private LayoutInflater mInflater;
Context context;
private String[] mStrings;
private TypedArray mIcons;
private int mViewResourceId;
ArrayList<String> selectedStrings = new ArrayList<String>();
public CheckboxAdapter(Context ctx, int viewResourceId, String[] strings) {
super(ctx, viewResourceId, strings);
mInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mStrings = strings;
mViewResourceId = viewResourceId;
}
public int getCount() {
return mStrings.length;
}
public String getItem(int position) {
return mStrings[position];
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mInflater.inflate(mViewResourceId, null);
final CheckBox tv = (CheckBox) convertView.findViewById(R.id.checkBox1);
tv.setText(mStrings[position]);
tv.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if (isChecked) {
selectedStrings.add(tv.getText().toString());
Toast.makeText(buttonView.getContext(),Boolean.toString(selectedStrings.add(tv.getText().toString())), Toast.LENGTH_SHORT).show();
} else {
selectedStrings.remove(tv.getText().toString());
}
}
});
return convertView;
}
}
This is my actvity
public class AddTime extends Activity {
CheckboxAdapter cadpter;
String daya[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thrusday",
"Friday", "Saturday" };
ListView list;
ArrayList<String> selectedStrings = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.addtime);
list = (ListView) findViewById(R.id.listView1);
cadpter = new CheckboxAdapter(AddTime.this, R.layout.list_item, daya);
list.setAdapter(cadpter);
}
}
I am displaying all day in listview also i have display check box with each day when i enable check box it show true in toast but i want what ever i select day using check box i mean i want display all the day in textview in mainactvity please suggest me how i will get it .
how to get all checked value on button click from list-view in android
As adding all checked values in selectedStrings ArrayList. create a method in CheckboxAdapter class which return ArrayList of all selected values. for example :
public ArrayList<String> getAllSelectedValues(){
return this.selectedStrings;
}
Now use cadpter CheckboxAdapter class object for accessing getAllSelectedValuesmethod in Activity:
ArrayList<String> selectedStrings=cadpter.getAllSelectedValues();
get all values from selectedStrings arrayList
for(int i=0;i<=selectedStrings.sizes();i++){
String s =selectedStrings.get(i);
}
Take boolean Array
ArrayList<Boolean> selectedStrings = new ArrayList<>();
and add onClickListener in your checkbox
public View getView(final int position, View convertView, ViewGroup parent) {
-
-
tv.setChecked(false);
if(selectedStrings.size() <= position){
selectedStrings.add(position, false);
}else
tv.setChecked(selectedStrings.get(position));
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean state = selectedStrings.get(position);
selectedStrings.remove(position);
selectedStrings.add(position, state ? false : true);
}
});
}
This is my custom list adapter. I want to update the values in table using the update ImageButton in the list. On clicking it, the old values should be shown in a new activity and then the edited value must be stored in the database. However, I am unable to pass an intent inside the onClick() method.
Please suggest me a solution
public class CustomListAdapter extends BaseAdapter implements ListAdapter
{
private ArrayList<String> list = new ArrayList<String>();
private Context context;
OnItemSelectedListener onItemSelectedListener;
public int pos;
String pass,pass2,edit,epass;
public CustomListAdapter(List list, Context context) {
this.list = (ArrayList<String>) list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
//pass2 = list.toString();
return list.get(pos);
}
//#Override
//public Long getItemId(int pos) {
//
// //just return 0 if your list items do not have an Id variable.
//}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.layout_custom_list, null);
}
//Handle TextView and display string from your list
final TextView listItemText = (TextView)view.findViewById(R.id.list_item_string);
listItemText.setText(list.get(position));
//Handle buttons and add onClickListeners
ImageButton deleteBtn = (ImageButton)view.findViewById(R.id.delete_btn);
ImageButton editBtn = (ImageButton)view.findViewById(R.id.edit_btn);
//Button addBtn = (Button)view.findViewById(R.id.add_btn);
deleteBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something
list.remove(position);
pass = listItemText.getText().toString();
notifyDataSetChanged();
pass2 = pass.substring(0,pass.indexOf(' '));
System.out.println(pass2);
Moneydb.delete(pass2);
}
});
editBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v2) {
// TODO Auto-generated method stub
edit=listItemText.getText().toString();
epass = listItemText.getText().toString();
edit = epass.substring(0,epass.indexOf(' '));
Moneydb.edit(edit);
}
});
return view;
}
protected Context getContext() {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
//return list.get(position).getId();
return 0;
}
public void clear() {
//CustomListAdapter collection = null;
// TODO Auto-generated method stub
list.clear();
notifyDataSetChanged();
}
I suggest you to assign and ContextMenu to your list view with two MenuItem, Edit and Delete and write associated code outside of adapter
or you can start Activity by :
Intent new_intent = new Intent(v.getRootView().getContext(),edit_activity.class);
new_intent.putExtra("Key","Value");
v.getRootView().getContext().startActivity(new_intent);
i think the first method is best ;)
I have got a listview which uses a special adapter to pass data into the listview from the database.But the problem is that I am only getting one listview item being repeated and the other details are not being displayed. When I put breakpoints and debug the project, all the details are being passed to the hashmap, but the listview is only showing one particular item repeatedly. The code is shown below:
static class ViewHolder {
TextView txtmername,txtmerid,txtmeradd,txtmermeasure;
Button btnselect;
}
private LayoutInflater mInflater;
public SpecialAdapter(Context ctx,List<HashMap<String, String>> listData, int resourceId, String[] columnTags, int[] columnIds) {
super(ctx, listData, resourceId, columnTags, columnIds);
ctx=MerchantList.this;
listData=listData;
resourceId=R.layout.merchant_listview;
columnTags=columnTags;
columnIds=columnIds;
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return super.getItem(position);
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid unneccessary calls
// to findViewById() on each row.
ViewHolder holder;
Context con=getApplicationContext();
if(convertView==null)
// convertView = getActivity().getLayoutInflater().inflate(R.layout.stores_listview_layout, pa
mInflater = (LayoutInflater)con.getSystemService(con.LAYOUT_INFLATER_SERVICE);
convertView=mInflater.inflate(R.layout.merchantlistview, null);
holder = new ViewHolder();
holder.txtmername = (TextView) convertView.findViewById(R.id.lblMerchantName);
holder.txtmeradd=(TextView)convertView.findViewById(R.id.lblAddress);
holder.txtmerid=(TextView)convertView.findViewById(R.id.lblMerchantId);
holder.txtmermeasure=(TextView)convertView.findViewById(R.id.lblMeasure);
holder.btnselect=(Button)convertView.findViewById(R.id.btnSelect);
holder.btnselect.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
});
convertView.setTag(holder);
if(convertView !=null)
{
holder=(ViewHolder)convertView.getTag();
// Binding the data efficiently with the holder
SQLiteDatabase db=openOrCreateDatabase("NEW.db", MODE_PRIVATE, null);
Cursor OrderCursor = db.rawQuery("SELECT DISTINCT(A.ID), B.NAME, B.ADDRESS, A.MEASURE FROM (SELECT ID, MIN( CAST(STOCK_IN_HAND AS REAL) /REORDER_LEVEL) AS MEASURE FROM INVENTORY GROUP BY ID) A INNER JOIN MASTER B ON A.ID=B.ID ORDER BY A.MEASURE", null);
listData.clear();
if(OrderCursor!= null)
{
if(OrderCursor.moveToFirst()){
for (int i = 0; i < OrderCursor.getCount(); i++){
// String first,second,third,fourth=null;
HashMap<String,String> map = new HashMap<String, String>();
map.put(columnTags[0], OrderCursor.getString(OrderCursor.getColumnIndex("NAME")));
map.put(columnTags[1], OrderCursor.getString(OrderCursor.getColumnIndex("ADDRESS")));
map.put(columnTags[2], OrderCursor.getString(OrderCursor.getColumnIndex("ID")));
map.put(columnTags[3], OrderCursor.getString(OrderCursor.getColumnIndex("MEASURE")));
listData.add(map);
String measure = map.get("measure").toString();
String name=map.get("Name").toString();
String address=map.get("Address").toString();
String id=map.get("Id").toString();
holder.txtmerchantname.setText(name);
holder.txtmeradd.setText(address);
holder.txtmerid.setText(id);
holder.txtmermeasure.setText(measure);
double measure1=Double.parseDouble(measure);
if(measure1 > 1.5)
{
convertView.setBackgroundColor(getResources().getColor(R.color.Green));
}
else if((1.5 >= measure1 ) && (measure1>1.0))
{
convertView.setBackgroundColor(getResources().getColor(R.color.Yellow));
}
else if(1.0>=measure1)
{
convertView.setBackgroundColor(Color.RED);
}
OrderCursor.moveToNext();
}//end of for
}
OrderCursor.close();
db.close();
}
}
return convertView;
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
#Override
public int getViewTypeCount() {
return super.getViewTypeCount();
}
}
Try using the following code which i guess will be helpful. Hence you are using the hashmap the arrayAdapter can be used.
https://stackoverflow.com/a/15061779/2106338
getViewTypeCount() is not matched with your listView items count therefore it adds up another item.
In your case I think its about the measure condition you are using.
In the end you should use else instead of else if
OR
if there is another condition, you must treat it.
I am using SQLiteDatabase in android. I am not able to refersh my listview after deleting a row.
My code is as follows:
public void delete(String i) {
// TODO Auto-generated method stub
String [] columns= new String[]{KEY_ROW_ID,KEY_FHR,KEY_ID,KEY_NAME,KEY_AGE};
Cursor c= our_db.query(KEY_TABLE, columns, null, null,null, null, null);
our_db.delete(KEY_TABLE, KEY_NAME+ "="+"\'"+i+"\'", null) ;
c.requery();
}
I call it from a viewholder in efficientadapter. Below is the code where I call it:
holder.del.setOnClickListener(new OnClickListener() {
private int pos=position;
public void onClick(View v) {
// TODO Auto-generated method stub
final long newpos;
sql_get db = new sql_get(c);
db.open();
db.delete(DATA[pos]);
notifyDataSetChanged();
db.close();
}
});
Can anyone help me finding out the problem. It doesn't give any error. it just deleted the row but doesn't update the view.
Here is the adapter i used:
private static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private Bitmap mIcon1;
private Bitmap mIcon2;
private Bitmap mIcon3;
private Bitmap mIcon4;
Context c;
int window;
public EfficientAdapter(Context context) {
// Cache the LayoutInflate to avoid asking for a new one each time.
mInflater = LayoutInflater.from(context);
this.c=context;
// Icons bound to the rows.
mIcon1 = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon48x48_1);
mIcon2 = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon48x48_2);
mIcon3 = BitmapFactory.decodeResource(context.getResources(), R.drawable.del1);
mIcon4 = BitmapFactory.decodeResource(context.getResources(), R.drawable.edit);
}
public int getCount() {
return DATA.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid unneccessary calls
// to findViewById() on each row.
ViewHolder holder;
//int i=0;
convertView = mInflater.inflate(R.layout.list_item_icon_text, null);
// Creates a ViewHolder and store references to the two children views
// we want to bind data to.
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.text);
holder.icon = (ImageView) convertView.findViewById(R.id.icon);
holder.del=(ImageView)convertView.findViewById(R.id.icon1);
holder.edit=(ImageView)convertView.findViewById(R.id.icon2);
window=position;
holder.text.setOnClickListener(new OnClickListener() {
private int pos=position;
//private int pos = position;
public void onClick(View v) {
System.out.println(window);
sql_get db = new sql_get(c);
db.open();
String ret_id= db.getid(DATA[pos]);
String ret_name = db.getname(DATA[pos]);
String ret_age= db.getage(DATA[pos]);
String ret_fhr= db.getfhr(DATA[pos]);
String[] result = {ret_id,ret_name,ret_age,ret_fhr};
db.close();
Bundle b=new Bundle();
b.putStringArray("key",result);
Intent i =new Intent(c,Tabs.class);
i.putExtras(b);
c.startActivity(i) ;
Toast.makeText(c, getItemId(position)+""+" Click- text " +pos+" "+ret_name, Toast.LENGTH_SHORT).show();
}
});
holder.del.setOnClickListener(new OnClickListener() {
private int pos=position;
public void onClick(View v) {
// TODO Auto-generated method stub
final long newpos;
sql_get db = new sql_get(c);
db.open();
db.delete(DATA[pos]);
notifyDataSetChanged();
db.close();
Toast.makeText(c, "deleting " + DATA[pos], Toast.LENGTH_SHORT).show();
}
});
convertView.setTag(holder);
}
holder.text.setText(DATA[position]);
holder.icon.setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2);
holder.del.setImageBitmap(mIcon3);
holder.edit.setImageBitmap(mIcon4);
return convertView;
static class ViewHolder {
ImageView del;
TextView text;
ImageView icon;
ImageView edit;
}
}
You need to delete the row also from the object holding the data for the list view..
I think you also have to remove the same data from adapter and then use your_adapter.notifyDataSetChanged() method. That worked for me...
I found the solution. As said above, I had to change the DATA object.
I used the following commands to achieve it.
db.open();
db.delete(DATA[pos]);
DATA=db.getdata();
DATA_NAME=db.getname();
DATA_AGE=db.getage();
DATA_FHR=db.getfhr();
db.close();
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