Retrieve selected data from checkbox from list in android - 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.

Related

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();
}
});

How to handle click event for a list view item with checkbox in Android listview?

I am using ArrayAdapter with android.R.layout.simple_list_item_multiple_choice for my list view. I have an onItemClick() handler for the list view that launches an activity which displays the selected item in detail.
I would like this activity launched only when the click happens outside the checkbox. And when the checkbox is clicked on, I want the checkbox status toggled and NOT launch the detail view activity. Currently, both happen always when clicked on anywhere in the list, which is not desired.
Is it possible? Or should I use a custom adapter and add a checkbox and onclick handler?
You can use custom Adapter class for this, and code that use custom adapter is
For ref check here
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);
// 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() ;
if ( planets == null ) {
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")
};
}
ArrayList<Planet> planetList = new ArrayList<Planet>();
planetList.addAll( Arrays.asList(planets) );
// 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 ;
}
}
you can do like this
public class MainActivity extends ActionBarActivity implements OnClickListener {
Button mbtn_submit;
ListView mlistview;
List<String> namesList;
ArrayAdapter<String> adapter;
String names[] = { "Divya", "Kavya", "Janu", "Anu", "Sneha", "Vistnu",
"Ravi", "Anil" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mlistview = (ListView) findViewById(R.id.listview);
mbtn_submit = (Button) findViewById(R.id.btn_submit);
namesList = new ArrayList<String>();
for (int i = 0; i < names.length; i++) {
namesList.add(names[i]);
}
adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_multiple_choice, namesList);
mlistview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mlistview.setAdapter(adapter);
mbtn_submit.setOnClickListener(this);
}
#Override
public void onClick(View v) {
SparseBooleanArray checked = mlistview.getCheckedItemPositions();
ArrayList<String> selectedItems = new ArrayList<String>();
for (int i = 0; i < checked.size(); i++) {
int position = checked.keyAt(i);
if (checked.valueAt(i))
selectedItems.add(adapter.getItem(position));
}
String[] selectedItemsArr = new String[selectedItems.size()];
for (int i = 0; i < selectedItems.size(); i++) {
selectedItemsArr[i] = selectedItems.get(i);
}
Intent intent = new Intent(MainActivity.this,
SelectedListActivity.class);
Bundle bundle = new Bundle();
bundle.putStringArray("selectedItems", selectedItemsArr);
intent.putExtras(bundle);
startActivity(intent);
}
}
and selectedList
public class SelectedListActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selected_list);
Bundle bundle = getIntent().getExtras();
String[] resultArr = bundle.getStringArray("selectedItems");
ListView lv = (ListView) findViewById(R.id.selectedList);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, resultArr);
lv.setAdapter(adapter);
}
}

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

if click on checkboxes my checklist should be save in Xml How?

My checkboxlist are displaying but i want to check some list item which will save in xml for further use. how ?here is my list code, preference .. please explain me with code that how it will save my checkbox list.
public class MachinesCheck extends Activity implements IObserver {
private StringBuffer buffer = new StringBuffer();
private ListView mainListView ;
private ArrayList<Machine> Machines ;
private ArrayList<Machine> SelectedMachines ;
private ArrayAdapter<Machine> listAdapter ;
Vector<MDCMachineStatus> machineStatus_vector;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.machinecheck);
SelectedMachines = new ArrayList<Machine>();
MachineStatusSingleton.Register(this);
getData();
// 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() {
public void onItemClick( AdapterView<?> parent, View item,
int position, long id) {
Machine machine = listAdapter.getItem( position );
machine.toggleChecked();
MachineViewHolder viewHolder = (MachineViewHolder) item.getTag();
viewHolder.getCheckBox().setChecked( machine.isChecked() );
if (machine.checked)
{
SelectedMachines.add(machine);
}
else
{
SelectedMachines.remove(machine);
}
}
});
listAdapter = new MachineArrayAdapter(this, Machines);
mainListView.setAdapter( listAdapter );
mainListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
private void getData(){
machineStatus_vector = MachineStatusSingleton.GetData();
//arrayListofMachines = new ArrayList<String>();
//arrayListofMachineNumbers = new ArrayList<String>();
Machines = new ArrayList<Machine>();
for(MDCMachineStatus temp: machineStatus_vector){
//arrayListofMachines.add(temp.toString());
//arrayListofMachineNumbers.add(temp.getNumber());
Machines.add(new Machine(temp.toString(), temp.getNumber()));
}
}
private static class Machine {
private String name = "" ;
private String number ="";
private boolean checked = false ;
public Machine() {}
public Machine( String name, String number ) {
this.name = name ;
this.number = number ;
}
public Machine( String name, boolean checked ) {
this.name = name ;
this.checked = checked ;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public String toString() {
return name ;
}
public void toggleChecked() {
checked = !checked ;
}
}
private static class MachineViewHolder {
private CheckBox checkBox ;
private TextView textView ;
public MachineViewHolder( 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;
}
}
private static class MachineArrayAdapter extends ArrayAdapter<Machine> {
private LayoutInflater inflater;
public MachineArrayAdapter( Context context, List<Machine> machineList ) {
super( context, R.layout.selectedlist, R.id.rowTextView, machineList );
// 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) {
// Machine to display
Machine machine = (Machine) 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.selectedlist, 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 MachineViewHolder(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 ;
Machine machine = (Machine) cb.getTag();
machine.setChecked( cb.isChecked() );
}
});
}
// Reuse existing row view
else {
// Because we use a ViewHolder, we avoid having to call findViewById().
MachineViewHolder viewHolder = (MachineViewHolder) 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( machine );
// Display planet data
checkBox.setChecked( machine.isChecked() );
textView.setText( machine.getName() );
return convertView;
}
}
public Object onRetainNonConfigurationInstance() {
return Machines ;
}
public void Update(ISubject arg0) {
// TODO Auto-generated method stub
}
}
and here is my preference please check and tell me how it saved the data im xml file.
<PreferenceScreen
android:key="DataEntryScreen"
android:title="Data Entry Machine"
android:summary="Select a Machine">
</PreferenceScreen>
Try this code to create xml, to save it use this string and write it to file.
private static StringWriter createXml(ArrayList<Machine> SelectedMachines) {
StringWriter writer = new StringWriter();
XmlSerializer serializer = Xml.newSerializer();
try {
serializer.setOutput(writer);
serializer.startDocument("UTF-8", true);
serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
serializer.startTag(null, "Machine");
for (Machine machine : SelectedMachines) {
serializer.startTag(null, "Name");
serializer.text(machine.getName());
serializer.endTag(null, "Name");
serializer.startTag(null, "Number");
serializer.text(machine.getNumber());
serializer.endTag(null, "Number");
}
if (serializer == null)
return null;
serializer.endTag(null, "Machine");
serializer.endDocument();
serializer.flush();
writer.close();
} catch (Exception e) {
Log.e("createXml", e.toString());
}
return writer;
}

Finding the Checked state of checkbox in a custom listview

Hai i'm trying to develop an app where by i can send sms and email to a particular group of people..
I have a listview showing the contacts which are in my group.Each row is of the form
TextView(Name)TextView(phone) Checkbox(sms)
TextView(email id) Checkbox(mail)
I have used custom adapter to display the contact details to the listview.ihave set the onitemclick listener to find the position of the row..
I have to send sms and email to those contacts for which checkboxes have been set as true.how can i find the state of each of the checkboxes.
Please help me..lotz of thanx in advance..
I hav added below the custom adapetr i hv created..
public class ContactInfoAdapter extends ArrayAdapter{
private ArrayList<Boolean> mChecked_sms,mChecked_email;
Context context;
int layoutResourceId;
ContactInfo data[] = null;
public ContactInfoAdapter(Context context, int layoutResourceId, ContactInfo[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
mChecked_sms = new ArrayList<Boolean>();
mChecked_email = new ArrayList<Boolean>();
for (int i = 0; i < this.getCount(); i++) {
mChecked_sms.add(i, false);
mChecked_email.add(i,false);
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ContactHolder holder;
View row = convertView;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ContactHolder();
holder.txtName = (TextView)row.findViewById(R.id.textViewName);
holder.txtPhone = (TextView) row.findViewById(R.id.textViewPhone);
holder.txtEmail = (TextView) row.findViewById(R.id.textViewEmail);
holder.cb_sms_state = (CheckBox) row.findViewById(R.id.checkBox1);
holder.cb_email_state = (CheckBox) row.findViewById(R.id.checkBox2);
row.setTag(holder);
}
else
{
holder = (ContactHolder)row.getTag();
}
ContactInfo contact = data[position];
holder.txtName.setText(contact.name);
holder.cb_sms_state.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (holder.cb_sms_state.isChecked()) {
mChecked_sms.set(position, true);
Toast.makeText(getContext(), "checked", 2).show();
} else {
mChecked_sms.set(position, false);
}
}
});
holder.cb_sms_state.setChecked(mChecked_sms.get(position));
holder.cb_email_state.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (holder.cb_email_state.isChecked()) {
mChecked_email.set(position, true);
Toast.makeText(getContext(), "checked", 2).show();
} else {
mChecked_email.set(position, false);
}
}
});
holder.cb_email_state.setChecked(mChecked_email.get(position));
holder.txtPhone.setText(contact.number);
holder.txtEmail.setText(contact.email);
return row;
}
static class ContactHolder
{
TextView txtName;
TextView txtPhone;
TextView txtEmail;
CheckBox cb_sms_state;
CheckBox cb_email_state;
}
}
The ContactInfo class is :
public class ContactInfo {
public String name;
public String number;
public String email;
public boolean sms_state;
public boolean email_state;
public ContactInfo(){
super();
}
public ContactInfo(String name,String number,String email,boolean sms_state,boolean email_state) {
super();
this.name = name;
this.number = number;
this.email = email;
this.sms_state = sms_state;
this.email_state = email_state;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setNUmber(String number) {
this.number = number;
}
public String getNumber() {
return number;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
public void setSms_state(Boolean sms_state)
{
this.sms_state = sms_state;
}
public Boolean getSms_state(){
return sms_state;
}
public void setEmail_state(Boolean email_state)
{
this.email_state = email_state;
}
public Boolean getEmail_state(){
return email_state;
}
Inside the getView() method, you have to implement a OnCheckedChangeListener for the CheckBox.
Here is a listener code, say for example:
ChkBx.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if ( isChecked )
{
// perform logic
}
}
});
See the doc.
I think you need :
checkbox.isChecked()
Here's a simple sample:
mContactListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long arg3) {
CheckBox chkContact = (CheckBox) view.findViewById(R.id.listrow_contact_chkContact);
if (chkContact.isChecked()) {
...
}
});
I've had this problem with my app Hasta La Vista I've create a with custom listview with checked items and I needed to get checked items this was the solution:
ListView lv = getListView(); //ver listview
if(lv != null){
final SparseBooleanArray checkedItems = lv.getCheckedItemPositions(); //get checked items
if (checkedItems == null) {
return;
}
final int checkedItemsCount = checkedItems.size();
for (int i = 0; i < checkedItemsCount; ++i) {
// This tells us the item position we are looking at
final int position = checkedItems.keyAt(i);
// This tells us the item status at the above position
final boolean isChecked = checkedItems.valueAt(i);
if(isChecked){
//get item from list and do something
lv.getAdapter().getItem(position);
}
}
}
As ListView views are recycled, you can not rely on listening on particular instance, you will have to store "checked" state in your data model. You will also need custom list adapter, where you create and populate individual entries. Following shall be done:
- in overriden getView(), either create new view ( in case no convertView was supplied ) or inflate new one
- populate viewv fields from you data model
- remove old onclick listener, and set new one ( can be anonymous inner class ) modifying your data model
PS: recycling views is important if your list is big

Categories

Resources