checkbox in listview for multiple selection of contacts - android

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

Related

redirecting itemchecked to a new activity

I have read and tried to follow some other threads from stackoverflow and I am not understanding how to get this to work.
Brief description. I have an activity that loads the contact list into a custom list view. I can select the contacts using a check box. I also have a done button and a cancel button. When the done button is selected it will take all the check box items and display the contacts in a new activity with its own custom list view.
My issue is how to set up my button click to display just the selected contacts.
here is my done button code very rough:
private Button mDoneButton, mCancelButton;
ListView guestListView;
ProgressDialog guestProgressDialog;
ArrayList<String> guestAA = new ArrayList<String>();
ArrayList<String> guestNum = new ArrayList<String>();
//ArrayList<String> guestEmail = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contacts);
guestListView = (ListView) findViewById(R.id.ListView);
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
guestProgressDialog = ProgressDialog.show(contactDisplayActivity.this, "Loading...", "Please Wait", true, false);
} //end of on PreExecute method
#Override
protected Void doInBackground(Void... params) {
getGuestContacts();
return null;
} //end of doInBackground method
#Override
protected void onPostExecute(Void result) {
//getGuestContacts();
guestProgressDialog.dismiss();
CustomAdapter guestCustomAdapter = new CustomAdapter(contactDisplayActivity.this);
guestListView.setAdapter(guestCustomAdapter);
} //end of onPostExecute Method
} .execute((Void[]) null);
//Done Button
mDoneButton = (Button)findViewById(R.id.doneButton);
mDoneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
long [] guestIds = guestListView.getCheckedItemIds();
for (long guestId : guestIds ) {
getGuestContacts();
}
Intent myIntent = new Intent(contactDisplayActivity.this, GuestList.class);
startActivity(myIntent);
}
});
//Cancel Button
mCancelButton = (Button)findViewById(R.id.cancelButton);
mCancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//mListener.onFragmentInteraction();
//((PlanMeMainActivity) getActivity()).newActivityToLaunch(1);
Intent myIntent = new Intent(contactDisplayActivity.this, EventDetails.class);
startActivity(myIntent);
}
});
}
private void getGuestContacts() {
ContentResolver guestContactResolver = getContentResolver();
Cursor guestCursor = guestContactResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (guestCursor.getCount() > 0) {
while (guestCursor.moveToNext()) {
String guestId = guestCursor.getString(guestCursor.getColumnIndex(ContactsContract.Contacts._ID));
String guestName = guestCursor.getString(guestCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
//String guestEmail = guestCursor.getString(guestCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS));
guestAA.add(guestName);
if (Integer.parseInt(guestCursor.getString(guestCursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor phoneCursor = guestContactResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{guestId}, null);
while (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
guestNum.add(phoneNumber);
}
//while (phoneCursor.moveToNext()) {
// String email = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS));
//guestEmail.add(email);
//}
phoneCursor.close();
}
}
}
}
public class CustomAdapter extends BaseAdapter {
private Context mContext;
public CustomAdapter(Context context) {
mContext = context;
}
public int getCount() {
return guestNum.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
final int pos = position;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.contacts_display, null);
holder.textviewName = (TextView) convertView.findViewById(R.id.contactsTextView1);
holder.textviewNumber = (TextView) convertView.findViewById(R.id.contactsTextView2);
//holder.textViewEmail = (TextView) convertView.findViewById(R.id.contactsTextView3);
holder.checkbox = (CheckBox) convertView.findViewById(R.id.contactsCheckBox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.checkbox.setId(position);
holder.textviewName.setId(position);
holder.textviewNumber.setId(position);
//holder.textViewEmail.setId(position);
holder.textviewName.setText(guestAA.get(position));
holder.textviewNumber.setText("No. " + guestNum.get(position));
//holder.textViewEmail.setText(guestEmail.get(position));
holder.id = position;
return convertView;
}
}
static class ViewHolder {
TextView textviewName;
TextView textviewNumber;
//TextView textViewEmail;
CheckBox checkbox;
int id;
}
}
the getGuestContacts method displays the contact list.
Any help or direction would be great. Thanks.

Using dynamically added checkbox to delete data from listview populated from database in android?

Hi I am building an android app that uses checkbox to delete checked data from SQLite database. I write this code to populate data from SQlite database.
public class DisplayAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> id;
private ArrayList<String> firstName;
private ArrayList<String> lastName;
public static ArrayList<Integer> position=new ArrayList<Integer>();
public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname) {
this.mContext = c;
this.id = id;
this.firstName = fname;
this.lastName = lname;
}
public int getCount() {
// TODO Auto-generated method stub
return id.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int pos, View child, ViewGroup parent) {
final Holder mHolder;
final int a=pos;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.listcell, null);
mHolder = new Holder();
mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);
mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
mHolder.checkbox = (CheckBox) child.findViewById(R.id.checkbox);
mHolder.checkbox.setTag(a);
position.add(a);
mHolder.checkbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(((CheckBox)v).isChecked()){
//Toast.makeText(mContext, ""+a,Toast.LENGTH_LONG).show();
}
}
});
child.setTag(mHolder);
} else {
mHolder = (Holder) child.getTag();
}
mHolder.txt_id.setText(id.get(pos));
mHolder.txt_fName.setText(firstName.get(pos));
mHolder.txt_lName.setText(lastName.get(pos));
return child;
}
public class Holder {
CheckBox checkbox;
TextView txt_id;
TextView txt_fName;
TextView txt_lName;
}
}
I have a button (Delete) on the listView activity.After checking the checkboxes When a user presses delete button It will delete the data which was cecked from database and show the rest of the data remaining in Database.
This is the activity where I am handling the click.
public class DisplayActivity extends Activity {
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private ArrayList<String> userId = new ArrayList<String>();
private ArrayList<String> user_fName = new ArrayList<String>();
private ArrayList<String> user_lName = new ArrayList<String>();
private ListView userList;
private AlertDialog.Builder build;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_activity);
userList = (ListView) findViewById(R.id.List);
mHelper = new DbHelper(this);
Button delete=(Button) findViewById(R.id.deleteBtn);
delete.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
if(userId.size()>0){
for(int i=0;i<DisplayAdapter.position.size();i++){
Toast.makeText(DisplayActivity.this, ""+i, Toast.LENGTH_SHORT).show();
View getView=userList.findViewWithTag(DisplayAdapter.position.get(i));
CheckBox checkbox = (CheckBox) getView
.findViewById(R.id.checkbox);
if(checkbox.isChecked()){
//Toast.makeText(DisplayActivity.this, ""+i, Toast.LENGTH_SHORT).show();
dataBase.delete(
DbHelper.TABLE_NAME,
DbHelper.KEY_ID + "="
+userId.get(i), null);
displayData();
}
}
}
} catch (Exception e) {
Toast.makeText(DisplayActivity.this, "Nothing Selected", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
});
//add new record
findViewById(R.id.btnAdd).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),
AddActivity.class);
i.putExtra("update", false);
startActivity(i);
}
});
//click to update data
userList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Intent i = new Intent(getApplicationContext(),
AddActivity.class);
i.putExtra("Fname", user_fName.get(arg2));
i.putExtra("Lname", user_lName.get(arg2));
i.putExtra("ID", userId.get(arg2));
i.putExtra("update", true);
startActivity(i);
}
});
}
#Override
protected void onResume() {
displayData();
super.onResume();
}
/**
* displays data from SQLite
*/
private void displayData() {
dataBase = mHelper.getWritableDatabase();
Cursor mCursor = dataBase.rawQuery("SELECT * FROM "
+ DbHelper.TABLE_NAME, null);
userId.clear();
user_fName.clear();
user_lName.clear();
if (mCursor.moveToFirst()) {
do {
userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
} while (mCursor.moveToNext());
}
DisplayAdapter disadpt = new DisplayAdapter(DisplayActivity.this,userId, user_fName, user_lName);
userList.setAdapter(disadpt);
mCursor.close();
}
}
It only deletes the first checked item from listview and as well databases.But i want to delete all the checked data from database.How do i do that? Details code and explanation would be appreciated. Thank in advance and sorry if i made any mistake.
I can give you a approach how you can implement this.
You can keep an ArrayList as a member variable and pass it to the constructor of DisplayAdapter. Whenever a user clicks your CheckCox add the position of the clicked item into your ArrayList and whenever user clicks it again just remove it from the ArrayList.
Then you can use an AsyncTask and in doInBackground() you can perform your delete operation from database and also delete data from ArrayList as well. Then inside your onpostExecute() you can call your notifyDatasetChanged() of your adapter.
The approach I use and thus recommend is this:
On your adapter add a checked callback:
List<YOUR_OBJ> checkedObjs;
onUserCheckBoxCallback callback;
...
public void OnCheckBoxCheckedCallback(onUserCheckBoxCallback callback) {
this.callback = callback;
}
//this part goes on bindView
yourCheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
callback.onUserCheckBoxChanged(your_obj.get(pos), isChecked);
}
});
if (checkedObjs!= null && checkedObjs.size() > 0)
yourCheckbox.setChecked(checkedObjs.contains(your_obj));
//this goes inside the adapter class
public interface onUserCheckBoxCallback {
void onUserCheckBoxChanged(YOUR_OBJECT_HERE, boolean isChecked);
}
And on your activity you simply do this:
declare your adapter
HashSet<YOUR_OBJ> checkedObjs;
...
//this part goes on onCreate()
adapter.OnCheckBoxCheckedCallback(new onUserCheckBoxCallback() {
#Override
public void onUserCheckBoxChanged(your_obj_type your_obj,boolean isChecked) {
if (isChecked)
checkedObjs.add(your_obj);
else
checkedObjs.remove(your_obj);
}
});
Just iterate trough this list deleting all the objects !
Hope it helps!

getting listview row data

I have a listview in my application.I want to set the value of textview in that particular row when I click one of the textview in that row itself.so,I tried like below
likes.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
TextView t=(TextView)v;
TextView likesnumber1 = (TextView) findViewById(R.id.likesnumber);
int i= Integer.parseInt(likescount.get(position));
if(like_or_ulike.get(position).equals("Like")){
Log.e("inlike","like");
like_or_ulike.set(position, "Unlike");
t.setText(like_or_ulike.get(position));
UrltoValue.getValuefromUrl("https://graph.facebook.com/"+objectid.get(position)+"/likes?access_token="+accesstoken+"&method="+"post");
j=i+1;
String s=Integer.toString(j);
likescount.set(position, s);
likesnumber1.setText(likescount.get(position));
}
else{
Log.e("unlike","unlike");
like_or_ulike.set(position, "Like");
t.setText(like_or_ulike.get(position));
UrltoValue.getValuefromUrl("https://graph.facebook.com/"+objectid.get(position)+"/likes?access_token="+accesstoken+"&method="+"DELETE");
j=i-1;
String s=Integer.toString(j);
likescount.set(position, s);
likesnumber1.setText(likescount.get(position));
}
}
});
the "likes" reference which I used is textview and I want to set the textview by getting the id of that particular row.
TextView likesnumber1 = (TextView) findViewById(R.id.likesnumber);
when I use this I am getting the id of the first visible row of the screen.
How can I get the id of textview of that particular row,on a textview click.
Thanks
I'm not sure how you are populating your list with data, however here is a method I use that works very well.
Data Models
public class Publication {
public String string1;
public String string2;
public Publication() {
}
public Publication(String string1, String string2) {
this.string1= string1;
this.string2= string2;
}
}
Create an array adapter
public class ContactArrayAdapter extends ArrayAdapter<ContactModel> {
private static final String tag = "ContactArrayAdapter";
private static final String ASSETS_DIR = "images/";
private Context context;
//private ImageView _emotionIcon;
private TextView _name;
private TextView _email;
private CheckBox _checkBox;
private List<ContactModel> contactModelList = new ArrayList<ContactModel>();
public ContactArrayAdapter(Context context, int textViewResourceId,
List<ContactModel> objects) {
super(context, textViewResourceId, objects);
this.context = context;
this.contactModelList = objects;
}
public int getCount() {
return this.contactModelList.size();
}
public ContactModel getItem(int index) {
return this.contactModelList.get(index);
}
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
// ROW INFLATION
Log.d(tag, "Starting XML Row Inflation ... ");
LayoutInflater inflater = (LayoutInflater) this.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.contact_list_entry, parent, false);
Log.d(tag, "Successfully completed XML Row Inflation!");
}
// Get item
final ContactModel contactModel = getItem(position);
Resources res = this.getContext().getResources();
//Here are some samples so I don't forget...
//
//_titleCount = (TextView) row.findViewById(R.id.category_count);
// _category.setText(categories1.Category);
//
//if (categories1.Category.equals("Angry")) {
//Drawable angry = res.getDrawable(R.drawable.angry);
//_emotionIcon.setImageDrawable(angry);
//}
_checkBox = (CheckBox) row.findViewById(R.id.contact_chk);
_email = (TextView) row.findViewById(R.id.contact_Email);
_name = (TextView)row.findViewById(R.id.contact_Name);
//Set the values
_checkBox.setChecked(contactModel.IsChecked);
_email.setText(contactModel.Email);
_name.setText(contactModel.Name);
_checkBox.setOnClickListener(new CompoundButton.OnClickListener() {
#Override
public void onClick(View view) {
if (contactModel.IsChecked) {
contactModel.IsChecked = false;
notifyDataSetChanged();
}
else {
contactModel.IsChecked = true;
notifyDataSetChanged();
}
}
});
return row;
}
}
Use the array adapter to fill your list
ContactArrayAdapter contactArrayAdapter;
//
List<ContactModel> contactModelList;
//Fill list with your method
contactModelList = getAllPhoneContacts();
//
contactArrayAdapter = new ContactArrayAdapter(getApplicationContext(), R.layout.contact_list_entry, contactModelList);
//
setListAdapter(contactArrayAdapter);
A sample method to fill data:
public List<ContactModel> getAllPhoneContacts() {
Log.d("START","Getting all Contacts");
List<ContactModel> arrContacts = new Stack<ContactModel>();
Uri uri = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
Cursor cursor = getContentResolver().query(uri, new String[] {ContactsContract.CommonDataKinds.Email.DATA1
,ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
,ContactsContract.CommonDataKinds.Phone._ID}, null , null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
cursor.moveToFirst();
while (cursor.isAfterLast() == false)
{
String email= cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
int phoneContactID = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
if (email != null)
{
ContactModel contactModel = new ContactModel();
contactModel.Name = name;
contactModel.Email = email;
contactModel.IsChecked = false;
arrContacts.add(contactModel);
}
cursor.moveToNext();
}
cursor.close();
cursor = null;
Log.d("END","Got all Contacts");
return arrContacts;
}
Accessing the data on click
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
//Click handler for listview
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View view, int position, long id) {
ContactModel contact= getItem(position);//This gets the data you want to change
//
some method here tochange set data
contact.email = "new#email.com"
//send notification
contactArrayAdapter.notifyDataSetChanged();
}
});

Retrieve selected data from checkbox from list in android

How can I retrieve selected data from a checkbox list?
I have made a list and put a checkbox in the list and now I want to retrieve the selected data from it.
how can I do this?
Here is my sample code
public class PlanetsActivity extends Activity {
private ListView mainListView;
private Planet[] planets;
private ArrayAdapter<Planet> listAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null);
// Find the ListView resource.
mainListView = (ListView) findViewById(R.id.mainListView);
// When item is tapped, toggle checked properties of CheckBox and
// Planet.
mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View item,
int position, long id) {
Planet planet = listAdapter.getItem(position);
planet.toggleChecked();
PlanetViewHolder viewHolder = (PlanetViewHolder) item.getTag();
viewHolder.getCheckBox().setChecked(planet.isChecked());
}
});
// Create and populate planets.
planets = (Planet[]) getLastNonConfigurationInstance();
// planets = new Planet[10];
// planets.Add("asdf");
ArrayList<Planet> planetList = new ArrayList<Planet>();
if (planets == null) {
if (cur.getCount() > 0) {
planets = new Planet[cur.getCount()] ;
int i=0;
while (cur.moveToNext()) {
String id = cur.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
//Toast.makeText(getApplicationContext(), name,
//Toast.LENGTH_LONG).show();
planets = new Planet[] { new Planet(name) };
planetList.addAll(Arrays.asList(planets));
//planets[i].setName(name);
//planets[i].setChecked(false)
if(Integer.
parseInt(cur
.getString(cur
.getColumnIndex(ContactsContract
.Contacts.HAS_PHONE_NUMBER))) > 0) {
// Query phone here. Covered next
}
i++;
}
}
// planets = new Planet[] { new Planet("Mercury"),
// new Planet("Venus"), new Planet("Earth"),
// new Planet("Mars"), new Planet("Jupiter"),
// new Planet("Saturn"), new Planet("Uranus"),
// new Planet("Neptune"), new Planet("Ceres"),
// new Planet("Pluto"), new Planet("Haumea"),
// new Planet("Makemake"), new Planet("Eris") };
}
// Set our custom array adapter as the ListView's adapter.
listAdapter = new PlanetArrayAdapter(this, planetList);
mainListView.setAdapter(listAdapter);
}
/** Holds planet data. */
private static class Planet {
private String name = "";
private boolean checked = false;
public Planet() {}
public Planet(String name) {
this.name = name;
}
public Planet(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. */
private static class PlanetViewHolder {
private CheckBox checkBox;
private TextView textView;
public PlanetViewHolder() {
}
public PlanetViewHolder(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 Planet objects. */
private static class PlanetArrayAdapter extends ArrayAdapter<Planet> {
private LayoutInflater inflater;
public PlanetArrayAdapter(Context context, List<Planet> 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) {
// Planet to display
Planet planet = (Planet) this.getItem(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 PlanetViewHolder(textView, checkBox));
// If CheckBox is toggled, update the planet it is tagged with.
checkBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Planet planet = (Planet) cb.getTag();
planet.setChecked(cb.isChecked());
}
});
}
// Reuse existing row view
else {
// Because we use a ViewHolder, we avoid having to call
// findViewById().
PlanetViewHolder viewHolder = (PlanetViewHolder) convertView
.getTag();
checkBox = viewHolder.getCheckBox();
textView = viewHolder.getTextView();
}
// Tag the CheckBox with the Planet it is displaying, so that we can
// access the planet in onClick() when the CheckBox is toggled.
checkBox.setTag(planet);
// Display planet data
checkBox.setChecked(planet.isChecked());
textView.setText(planet.getName());
return convertView;
}
}
public Object onRetainNonConfigurationInstance() {
return planets;
}
}
I want to send the selected data to next activity
You have just to pass your planets array in your intent, each beans on your array have a selected status ! But, to do that, before, Planet object need to implement Parcelable.

Clickable button in my database list

i have a list with data from my database.
I want to have a button in every list item that onClick will delete this item from the database.
Here is how i get the data from the db and present them in a list:
DB entry=new DB(this);
entry.open();
Cursor cursor = entry.getData();
startManagingCursor(cursor);
ListView list=(ListView)findViewById(R.id.list);
String[] columns = new String[] { DBHelper.NAME, DBHelper.SURNAME};
int[] to = new int[] { R.id.textView01,R.id.textView02};
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, R.layout.row, cursor, columns, to);
list.setAdapter(mAdapter);
entry.close();
So,my problem is : How to create a clickable button in every list item
EDIT:
this is the adapter i created:
public class myAdapter extends BaseAdapter {
private Context mContext;
final Drawable delete_btn;
private ImageButton imageButton;
private LayoutInflater inflater;
private List<ITEMS> items = new ArrayList<ITEMS>();
public myAdapter(Context ctx) {
mContext = ctx;
inflater = LayoutInflater.from(mContext);
delete_btn = ctx.getResources()
.getDrawable(R.drawable.delete_btn);
}
public View getView(final int position, View convertView, ViewGroup parent) {
View btv = null;
try {
btv = inflater.inflate(R.layout.row, null);
TextView name = (TextView) btv.findViewById(R.id.textView01);
name.setText(DBHelper.NAME);
TextView surname = (TextView) btv.findViewById(R.id.textView02);
surname.setText(DBHelper.SURNAME);
imageButton = (ImageButton) btv.findViewById(R.id.delete_btn);
imageButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(mContext, "Button pressed", Toast.LENGTH_LONG).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
return btv;
}
public void addItem(ITEM it) {
items.add(it);
}
public void setListItems(List<ITEM> lit) {
items = lit;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int arg0) {
return items.get(arg0);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
}
create your own CustomCursorAdapter instead of SimpleCursorAdapter. Here is an example

Categories

Resources