selecting multiple contacts using checkbox - android

I am trying to create a application for android. in which at one point i need to open a activity i need to display all the contacts on user's phone in a listview with checkbox, so that multiple contacts can be selected. I have written a code which currently shows the list of all the contacts but without checkbox as you can see in the image attached. Next, when the user selects the required contacts using checkbox and clicks on DONE button the result should be derived in main activity and all the contacts which the user selected should be displayed in the EditText like this Frank <+911234567890>, John <+913456789012>, Ashley <+911237890456>,. How can i achieve what i want? And also the dashes(-) which are currently getting displayed should also disappear.

Use the following to add checkboxes on all the items:
listView.setChoiceMode(CHOICE_MODE_MULTIPLE);
Not only will this add checkboxes to all the items, but it will handle all the check states for you. You have several methods you can use to get the state of the items:
getCheckedItemCount()
getCheckedItemIds()
getCheckedItemPositions()
And you can use setItemChecked() to set any item's checked state programmatically. Take a look at this tutorial for a guide how to make a multiple selection list.

split the string on each '-' using function split("-") and then concatenate it.

use the code snippet below to retrieve all contacts from the phonebook,append them in a ListView containing checkboxes to enable multiple selection,,it is clear and straight to the point.
public class Display extends Activity implements OnItemClickListener{
List<String> name1 = new ArrayList<String>();
List<String> phno1 = new ArrayList<String>();
MyAdapter ma ;
Button select;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
getAllContacts(this.getContentResolver());
ListView lv= (ListView) findViewById(R.id.lv);
ma = new MyAdapter();
lv.setAdapter(ma);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
// adding
select = (Button) findViewById(R.id.button1);
select.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
StringBuilder checkedcontacts= new StringBuilder();
for(int i = 0; i < name1.size(); i++)
{
if(ma.mCheckStates.get(i)==true)
{
checkedcontacts.append(name1.get(i).toString());
checkedcontacts.append("\n");
}
else
{
}
}
Toast.makeText(Display.this, checkedcontacts,1000).show();
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
ma.toggle(arg2);
}
public void getAllContacts(ContentResolver cr) {
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
name1.add(name);
phno1.add(phoneNumber);
}
phones.close();
}
class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
{ private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1,tv;
CheckBox cb;
MyAdapter()
{
mCheckStates = new SparseBooleanArray(name1.size());
mInflater = (LayoutInflater)Display.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.row, null);
tv= (TextView) vi.findViewById(R.id.textView1);
tv1= (TextView) vi.findViewById(R.id.textView2);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText("Name :"+ name1.get(position));
tv1.setText("Phone No :"+ phno1.get(position));
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
}

Related

Retrieving mobile contacts are displaying twice in the application

i am retriving mobile contact data to my app using ListView but data display two time in the List. help me how to Control of displaying contact two times.
I Refered and many solution through web , yet i am not able to sove.
i attached code below:
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private static final int PERMISSIONS_REQUEST_READ_CONTACTS = 100;
List<String> name1 = new ArrayList<String>();
List<String> phno1 = new ArrayList<String>();
MyAdapter ma ;
Button select;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS);
getAllContacts(this.getContentResolver());
ListView lv = (ListView) findViewById(R.id.lv);
ma = new MyAdapter();
lv.setAdapter(ma);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
}else {
getAllContacts(this.getContentResolver());
ListView lv = (ListView) findViewById(R.id.lv);
ma = new MyAdapter();
lv.setAdapter(ma);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
}
select = (Button) findViewById(R.id.button1);
select.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
StringBuilder checkedcontacts= new StringBuilder();
System.out.println(".............."+ma.mCheckStates.size());
for(int i = 0; i < name1.size(); i++)
{
if(ma.mCheckStates.get(i)==true)
{
checkedcontacts.append(name1.get(i).toString());
checkedcontacts.append("\n");
}
else
{
System.out.println("Not Checked......"+name1.get(i).toString());
}
}
Toast.makeText(MainActivity.this, checkedcontacts,Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
ma.toggle(arg2);
}
public void getAllContacts(ContentResolver cr) {
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.SORT_KEY_PRIMARY);
while (phones.moveToNext())
{
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println(".................."+phoneNumber +" >> "+ name);
name1.add(name);
phno1.add(phoneNumber);
}
phones.close();
}
class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
{ private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1,tv;
CheckBox cb;
MyAdapter()
{
mCheckStates = new SparseBooleanArray(name1.size());
mInflater = (LayoutInflater)MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.row, null);
TextView tv= (TextView) vi.findViewById(R.id.textView1);
tv1= (TextView) vi.findViewById(R.id.textView2);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText("Name :"+ name1.get(position));
tv1.setText("Phone No :"+ phno1.get(position));
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
System.out.println("hello...........");
notifyDataSetChanged();
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}}
my output :
It is because storage is returning the contacts twice ,they'll be duplicated because of google contacts,so when you retrieve just put a condition to exclude contacts which are already in.
public void getAllContacts(ContentResolver cr) {
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.SORT_KEY_PRIMARY);
while (phones.moveToNext())
{
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if(!phno1.contains(phoneNumber)) { // check wether contact already exists
name1.add(name);
phno1.add(phoneNumber);
}
}
phones.close();
}

Update listview when run onResume() in Android

I create a listview get all contact from address book of Android. I try to update listview by onResume() but It's not working.
Here is my code:
public class Display extends Activity implements OnItemClickListener{
List<String> name1 = new ArrayList<String>();
List<String> phno1 = new ArrayList<String>();
List<String> email1 = new ArrayList<String>();
MyAdapter ma ;
ListView lv;
int countContact;
TextView textViewManyCount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
getAllContacts(this.getContentResolver());
lv= (ListView) findViewById(R.id.lv);
ma = new MyAdapter();
lv.setAdapter(ma);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
textViewManyCount = (TextView) findViewById(R.id.textViewManyCount);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
public void getAllContacts(ContentResolver cr) {
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
countContact = phones.getCount();
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String email = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
System.out.println(".................."+phoneNumber);
name1.add(name);
phno1.add(phoneNumber);
email1.add(email);
}
phones.close();
}
class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
{ private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView textViewName,textViewPhone,textViewEmail;
MyAdapter()
{
mCheckStates = new SparseBooleanArray(name1.size());
mInflater = (LayoutInflater)Display.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.list_user, null);
textViewName = (TextView) vi.findViewById(R.id.textViewName);
textViewPhone = (TextView) vi.findViewById(R.id.textViewPhone);
textViewEmail = (TextView) vi.findViewById(R.id.textViewEmail);
textViewName.setText("Name :"+ name1.get(position));
textViewPhone.setText("Phone No :"+ phno1.get(position));
textViewEmail.setText("Email :"+ email1.get(position));
textViewManyCount.setText("Contacts: "+countContact);
return vi;
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
}
}
When I running app, It's load all contact but when I click button Home and change some information in Address book then click icon app to open app again. And onResume() method not working.
Here my onResume()
#Override
protected void onResume()
{
super.onResume();
if (lv != null)
{
updateData();
}
}
private void updateData()
{
getAllContacts(this.getContentResolver());
ma = new MyAdapter();
lv.setAdapter(ma);
ma.notifyDataSetChanged();
}
So some body help me! Plz!
Try by Replacing your updateData():
private void updateData()
{
getAllContacts(this.getContentResolver());
ma.notifyDataSetChanged();
}
You may be referencing an old ListView (lv) that is not the new ListView you see when you resume your Activity. Try getting the reference to lv again using Activity.findViewById(R.id.xxxx) in onResume().
You could also try reusing the old adapter instead of creating a brand new one (by clearing it and updating it's content). If you're reusing the old adapter, just make sure you give the old adapter to the new ListView using ListView.setAdapter(ma).
You should also have MyAdapter.getItemId(int position) return position instead of 0.

Select multiple contacts from phone book in android

I need to select contact numbers/emails from phone book in android.
I have seen selecting one contact and getting the result back in onActivityResult from this link.
But I need multiple contacts to be selected from the phone book. How to achieve this?
I don't want to make my custom list, is there a way to use androids built in functionality?
I am sharing code for select multiple contact from Phone Book. you have change little bit and you can achieve your goal. thanks
getAllContacts(this.getContentResolver());
ListView lv = (ListView) findViewById(R.id.lv);
ma = new MyAdapter();
lv.setAdapter(ma);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
// adding
select = (Button) findViewById(R.id.button1);
select.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
StringBuilder checkedcontacts = new StringBuilder();
for (int i = 0; i < name1.size(); i++)
{
if (ma.mCheckStates.get(i) == true) {
checkedcontacts.append(name1.get(i).toString());
checkedcontacts.append("\n");
} else {
}
}
Toast.makeText(Display.this, checkedcontacts, 1000).show();
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
ma.toggle(arg2);
}
public void getAllContacts(ContentResolver cr) {
Cursor phones = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, null);
while (phones.moveToNext()) {
String name = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
name1.add(name);
phno1.add(phoneNumber);
}
phones.close();
}
class MyAdapter extends BaseAdapter implements
CompoundButton.OnCheckedChangeListener {
private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1, tv;
CheckBox cb;
MyAdapter() {
mCheckStates = new SparseBooleanArray(name1.size());
mInflater = (LayoutInflater) Display.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
View vi = convertView;
if (convertView == null)
vi = mInflater.inflate(R.layout.row, null);
tv = (TextView) vi.findViewById(R.id.textView1);
tv1 = (TextView) vi.findViewById(R.id.textView2);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText("Name :" + name1.get(position));
tv1.setText("Phone No :" + phno1.get(position));
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
Looks like there's no such 'official' way. Your question is basically the same as this one How to select multiple contacts with Android SDK which has reference to custom implementation.
If You check AOSP Contacts application, there's no such possibility neither in documentation. The only thing I've observed from the source of AOSP Contacts is the following mention (in com.android.contacts.activities.PeopleActivity):
// TODO fix or remove multipicker code
// else if (resultCode == RESULT_CANCELED && mMode == MODE_PICK_MULTIPLE_PHONES) {
From MMS app source code You can observe the following (in ComposeMessageActivity):
private void launchMultiplePhonePicker() {
Intent intent = new Intent(Intents.ACTION_GET_MULTIPLE_PHONES);
intent.addCategory("android.intent.category.DEFAULT");
intent.setType(Phone.CONTENT_TYPE);
// We have to wait for the constructing complete.
ContactList contacts = mRecipientsEditor.constructContactsFromInput(true);
int urisCount = 0;
Uri[] uris = new Uri[contacts.size()];
urisCount = 0;
for (Contact contact : contacts) {
if (Contact.CONTACT_METHOD_TYPE_PHONE == contact.getContactMethodType()) {
uris[urisCount++] = contact.getPhoneUri();
}
}
if (urisCount > 0) {
intent.putExtra(Intents.EXTRA_PHONE_URIS, uris);
}
startActivityForResult(intent, REQUEST_CODE_PICK);
}
Field Intents.ACTION_GET_MULTIPLE_PHONES is available in ContactsContract.java but I wasn't able to find any usage of it across AOSP. So, I think it's some dead code or that action get handled in some closed code.
I've tried the same way to launch contacts selection from my test application and got only exception about no application to handle the action.
Of course, vendors Contacts applications provide such abilities (e.g. then selecting messages recipient), but it's better not to rely on them.
Though below code giving me multiple contacts
final int REQUEST_CODE_PICK_CONTACT = 57;
private void MultiplePhonePicker() {
Intent intent = new Intent("intent.action.INTERACTION_TOPMENU");
intent.putExtra("additional", "phone-multi");
startActivityForResult(intent, REQUEST_CODE_PICK_CONTACT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
switch (requestCode) {
case REQUEST_CODE_PICK_CONTACT:
switch (resultCode) {
case RESULT_OK:
Bundle bundle = intent.getExtras();
ArrayList<String> contacts = bundle.getStringArrayList("result");
break;
}
break;
}
}

android match contact from contactlist

I have try this code..it is working fine..
public class Test extends Activity implements OnItemClickListener{
List<String> name1 = new ArrayList<String>();
List<String> name2 = new ArrayList<String>();
List<String> phno1 = new ArrayList<String>();
List<String> matchedList;
MyAdapter ma ;
Button select;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name2.add("Abc");
name2.add("Xyz");
name2.add("Pqr");
name2.add("aaa");
getAllContacts(this.getContentResolver());
ListView lv= (ListView) findViewById(R.id.lv);
ma = new MyAdapter();
lv.setAdapter(ma);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
public void getAllContacts(ContentResolver cr) {
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println(".................."+phoneNumber);
name1.add(name);
phno1.add(phoneNumber);
}
phones.close();
}
class MyAdapter extends BaseAdapter
{
LayoutInflater mInflater;
TextView tv1,tv;
MyAdapter()
{
// mCheckStates = new SparseBooleanArray(name1.size());
mInflater = (LayoutInflater)Test.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.row_list, null);
TextView tv= (TextView) vi.findViewById(R.id.txt_name);
tv1= (TextView) vi.findViewById(R.id.txt_phoneNo);
tv.setText("Name :"+ name1.get(position));
// tv1.setText("Phone No :"+ phno1.get(position));
return vi;
}
}
}
Now in ArrayList name1 I am having list of all name of my device..
and in name2 i am having Arraylist of some selcected person..Now i want to match both of this array list and display name in list that is present....
I am working on this since last week..stuck here .. Please help me...
Thanks ...:)
Don't panic, just match both list and take one temp arraylist and when any name match then add in that temp arraylist and then show that list view according to that temp arraylist. :)
Here I give you code and hint:
ArrayList<String> matchname = new ArrayList<String>();
for(int k =0;k<name1;k++)
{
for(int l =0;l<name2.size();l++)
{
String keyname = name1[k];
if((keyname.trim().equals(name2[l].trim())))
{
matchname.add(keyname);
}
}
}

Listvew with textview and checkbox

I want to have a listview with textview + check box. I was able to create the listview. I can capture listview item select. However when I try to capture check box select, unselect I get a null pointer exception. How to write the setOnCheckedChangeListener() for the check box..
public class LocationActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.locationmain);
ListView listview = (ListView) findViewById(R.id.listView1);
String selectQuery = "SELECT * FROM " + DatabaseHandler.TABLE_LOCATIONLABLES;
SQLiteDatabase db = new DatabaseHandler(this).getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
final List<String> locLables = new ArrayList<String>();
if(cursor != null){
if (cursor.moveToFirst()) {
do {
locLables.add(cursor.getString(1));
} while (cursor.moveToNext());
}
}
//String[] locLables = new String[] {"Home","University","Office"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.locationmain_entry,R.id.textView12, locLables);
//cb gives a null pointer exception
CheckBox cb = (CheckBox) listview.findViewById(R.id.checkBox12);
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
System.out.println("selected");
}else if(!isChecked){
System.out.println("not selected");
}
}
});
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), locLables.get(arg2), Toast.LENGTH_SHORT).show();
}
});
}
You can maintain seperate adpater class so that you can achive this easily....
public class bsAdapter extends BaseAdapter
{
Activity cntx;
public bsAdapter(Activity context)
{
// TODO Auto-generated constructor stub
this.cntx=context;
}
public int getCount()
{
// TODO Auto-generated method stub
return listview_arr.length;
}
public Object getItem(int position)
{
// TODO Auto-generated method stub
return listview_arr[position];
}
public long getItemId(int position)
{
// TODO Auto-generated method stub
return listview_array.length;
}
public View getView(final int position, View convertView, ViewGroup parent)
{
View row=null;
LayoutInflater inflater=cntx.getLayoutInflater();
row=inflater.inflate(R.layout.search_list_item, null);
TextView tv=(TextView)row.findViewById(R.id.title);
CheckBox cb=(CheckBox)row.findViewById(R.id.cb01);
tv.setText(listview_arr[position]);
cb.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
if(cb.ischecked)
{
//ur code
}
else //ur code
}
});
return row;
}
}
Do not use listview.findViewById(), just use findViewById() like you did for your list.
Unless the checkbox is part of each of the list items, in which case you would have to access the checkbox from within the getView() of your ListAdapter.

Categories

Resources