Android Contact Picker With Checkbox - android

There are a lot of discussions going on about the same subject, but after spending 4 hours here, I could not find a valid description or a link to make a Contact Picker with Checkbox.
I have an activity with DONE button and listview with checkbox. I have managed to show the contacts correctly. Now I want to return the selected contact phone numbers in a bundle (I think the best way) so that I can get the list of numbers in onActivityResult(). I am not sure of the way I am following is right or not.
Here is my code:
public class ContactPickerMulti extends ListActivity implements OnClickListener {
// List variables
public String[] Contacts = {};
public int[] to = {};
public ListView myListView;
Button save_button;
private TextView phone;
private String phoneNumber;
private Cursor cursor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contacts_multi);
// Initializing the buttons according to their ID
save_button = (Button) findViewById(R.id.contact_done);
// Defines listeners for the buttons
save_button.setOnClickListener(this);
Cursor mCursor = getContacts();
startManagingCursor(mCursor);
ListAdapter adapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_multiple_choice,
mCursor,
Contacts = new String[] { ContactsContract.Contacts.DISPLAY_NAME },
to = new int[] { android.R.id.text1 });
setListAdapter(adapter);
myListView = getListView();
myListView.setItemsCanFocus(false);
myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
private Cursor getContacts() {
// Run query
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME };
String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + " = '"
+ ("1") + "'";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
return managedQuery(uri, projection, selection, selectionArgs,
sortOrder);
}
public void onClick(View src) {
Intent i;
switch (src.getId()) {
case R.id.contact_done:
SparseBooleanArray selectedPositions = myListView
.getCheckedItemPositions();
SparseBooleanArray checkedPositions = myListView
.getCheckedItemPositions();
if (checkedPositions != null) {
for (int k = 0; k < checkedPositions.size(); k++) {
if (checkedPositions.valueAt(k)) {
String name =
((Cursor)myListView.getAdapter().getItem(k)).getString(1);
Log.i("XXXX",name + " was selected");
}
}
}
break;
}
}
}
I want to send the numbers as array or list. What is the best way to do this? Any help or leading to right path is highly appreciated.

I use this code in onClick:
long[] id = getListView().getCheckedItemIds();// i get the checked contact_id instead of position
phoneNumber = new String[id.length];
for (int i = 0; i < id.length; i++) {
phoneNumber[i] = getPhoneNumber(id[i]); // get phonenumber from selected id
}
Intent pickContactIntent = new Intent();
pickContactIntent.putExtra("PICK_CONTACT", phoneNumber);// Add checked phonenumber in intent and finish current activity.
setResult(RESULT_OK, pickContactIntent);
finish();
//
private String getPhoneNumber(long id) {
String phone = null;
Cursor phonesCursor = null;
phonesCursor = queryPhoneNumbers(id);
if (phonesCursor == null || phonesCursor.getCount() == 0) {
// No valid number
signalError();
return null;
} else if (phonesCursor.getCount() == 1) {
// only one number, call it.
phone = phonesCursor.getString(phonesCursor
.getColumnIndex(Phone.NUMBER));
} else {
phonesCursor.moveToPosition(-1);
while (phonesCursor.moveToNext()) {
// Found super primary, call it.
phone = phonesCursor.getString(phonesCursor
.getColumnIndex(Phone.NUMBER));
break;
}
}
return phone;
}
private Cursor queryPhoneNumbers(long contactId) {
ContentResolver cr = getContentResolver();
Uri baseUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,
contactId);
Uri dataUri = Uri.withAppendedPath(baseUri,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY);
Cursor c = cr.query(dataUri, new String[] { Phone._ID, Phone.NUMBER,
Phone.IS_SUPER_PRIMARY, RawContacts.ACCOUNT_TYPE, Phone.TYPE,
Phone.LABEL }, Data.MIMETYPE + "=?",
new String[] { Phone.CONTENT_ITEM_TYPE }, null);
if (c != null && c.moveToFirst()) {
return c;
}
return null;
}
And the last onActivityResult of activity which you start PickContactsActivity
// TODO Auto-generated method stub
// super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == Constants.REQUEST_CODE_PICK_CONTACT) {
if (data != null) {
String[] temp = data.getStringArrayExtra("PICK_CONTACT");
}
}
}
}

When using startActivityForResult(newActivity) in the newActivity you must make a call to setResult(RESULT_OK) followed by finish() to close the Activity. Optionally you can include an Intent in the call to setResult(RESULT_OK, intent). The call to setResult() will lead to calling your implementation of onActivityResult() where you can handle the result of the Activity. So in your case you would just create an Intenet and add your array list to it using one of the putExtra() methods. That Intent will then be passed to onActivityResult() where you can extract that information. See Intent and Activity for more information.

Related

Contacts aren't showing up on my edittext

So i've been trying to add contact to a edittext,i've used Onclickevent to invoke contacts and then once a contact has been selected,it should be written to edittext,but i'm not able to do that,below is my Onactivity result,
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
Cursor cursor = null;
String name = "";
try {
Uri result = data.getData();
//writeToFile("uri" +result);
String id = result.getLastPathSegment();
// query for name
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?", new String[] { id },
null);
if (cursor != null && cursor.moveToFirst())
{
int phoneIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA);
int nameIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
writeToFile("ifcursor" +phoneIdx+nameIdx);
name = cursor.getString(nameIdx);
}
} catch (Exception e) {
//Log.e(DEBUG_TAG, "Failed to get name", e);
} finally {
if (cursor != null) {
cursor.close();
}
// phNo = (EditText) findViewById(R.id.phone_number);
phNo.setText(name);
if (name.length() == 0) {
Toast.makeText(getApplicationContext(),"Name not found for contact.",Toast.LENGTH_LONG).show();
}
}
break;
}
} else {
//Log.w(DEBUG_TAG, "Warning: activity result not ok");
}
}
any help would be deeply appreciated,it stucks on "name not found"
Try this one
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request it is that we're responding to
if (requestCode == PICK_CONTACT_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// Get the URI that points to the selected contact
Uri contactUri = data.getData();
// We only need the NUMBER column, because there will be only one row in the result
String[] projection = {Phone.NUMBER};
// Perform the query on the contact to get the NUMBER column
// We don't need a selection or sort order (there's only one result for the given URI)
// CAUTION: The query() method should be called from a separate thread to avoid blocking
// your app's UI thread. (For simplicity of the sample, this code doesn't do that.)
// Consider using CursorLoader to perform the query.
Cursor cursor = getContentResolver()
.query(contactUri, projection, null, null, null);
cursor.moveToFirst();
// Retrieve the phone number from the NUMBER column
int column = cursor.getColumnIndex(Phone.DISPLAY_NAME);
String number = cursor.getString(column);
phNo.setText(number );
// Do something with the phone number...
}
}
}
If you need the user to pick a contact with a phone number, you should call the following intent:
Intent i = new Intent(Intent.ACTION_PICK, Phone.CONTENT_URI);
startActivityForResult(i, CONTACT_PICKER_RESULT);
Then you can handle the response in onActivityResult like so:
Uri result = data.getData();
// because we asked for a Phone.CONTENT_URI picker, we'll get a uri for a Phone._ID entry
String id = result.getLastPathSegment();
String[] projection = new String[] { Phone.DISPLAY_NAME, Phone.NUMBER };
String selection = Phone._ID + "=" + id;
Cursor cursor = getContentResolver().query(Phone.CONTENT_URI, projection, selection,null, null);
if (cursor != null && cursor.moveToFirst()) {
String name = cursor.getString(0);
String number = cursor.getString(1);
Log.d("MyActivity", "got name=" + name + ", phone=" + number);
}
if (cursor != null) {
cursor.close();
}

Pick a number from calllog without repeating the same number

I want user to select a number from calllog and that number get selected and come in the activity. So I created custom calllog list. I used this code but it is not showing the call log list in right order
first thing it is showing the callhistory of the first number fully that it gets in the calllog list
second I wnt to show the name also, I tried a lot but I am not able to do
Can anyone tell what amendments i make in this code to make it right
The code I used is:
String[] callLogFields = { android.provider.CallLog.Calls._ID,
android.provider.CallLog.Calls.NUMBER,
android.provider.CallLog.Calls.CACHED_NAME };
String viaOrder = android.provider.CallLog.Calls.DATE + " DESC";
String WHERE = android.provider.CallLog.Calls.NUMBER + " >0"; /*filter out private/unknown numbers */
final Cursor callLog_cursor = this.getContentResolver().query(
android.provider.CallLog.Calls.CONTENT_URI, callLogFields,
WHERE, null, viaOrder);
AlertDialog.Builder myversionOfCallLog = new AlertDialog.Builder(this);
android.content.DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int item) {
callLog_cursor.moveToPosition(item);
Log.v("number", callLog_cursor.getString(callLog_cursor
.getColumnIndex(android.provider.CallLog.Calls.NUMBER)));
callLog_cursor.close();
}
};
myversionOfCallLog.setCursor(callLog_cursor, listener,
android.provider.CallLog.Calls.NUMBER);
myversionOfCallLog.setTitle("Choose from Call Log");
myversionOfCallLog.create().show();
You can add the Contact Numbers in a Set, which will prevent adding duplicate contact numbers. Then add the Set's data to listview as you want.
Set<String> setNumbers = new HashSet<String>();
String callNumber = cursor.getString(cursor.getColumnIndex(
android.provider.CallLog.Calls.NUMBER));
setNumbers.add(callNumber);
Hope this helps.
For saving numbers without duplicates, as MysticMagic suggested, use 'Set' as per the link given in the comment.
For getting the contact name from the phone number, use code :
(Reference)
private String getContactName(Context context, String number) {
String name = null;
// define the columns I want the query to return
String[] projection = new String[] {
ContactsContract.PhoneLookup.DISPLAY_NAME,
ContactsContract.PhoneLookup._ID};
// encode the phone number and build the filter URI
Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
// query time
Cursor cursor = context.getContentResolver().query(contactUri, projection, null, null, null);
if(cursor != null) {
if (cursor.moveToFirst()) {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
Log.v(TAG, "Started uploadcontactphoto: Contact Found # " + number);
Log.v(TAG, "Started uploadcontactphoto: Contact name = " + name);
} else {
Log.v(TAG, "Contact Not Found # " + number);
}
cursor.close();
}
return name;
}
Also refer here for another method to fetch name in phone call history
Uri allCalls = Uri.parse("content://call_log/calls");
Cursor c = managedQuery(allCalls, null, null, null, null);
String num= c.getString(c.getColumnIndex(CallLog.Calls.NUMBER));// for number
String name= c.getString(c.getColumnIndex(CallLog.Calls.CACHED_NAME));// for name
String duration = c.getString(c.getColumnIndex(CallLog.Calls.DURATION));// for duration
int type = Integer.parseInt(c.getString(c.getColumnIndex(CallLog.Calls.TYPE)));// for call type, Incoming or out going
Finally this is the code that worked with the help of MysticMagic and Nishanthi Grashia
Set setA;
setA = new HashSet();
public void getCallLog() {
try {
final String[] projection = null;
final String selection = null;
final String[] selectionArgs = null;
final String sortOrder = "DATE DESC";
final Cursor cursor = this.getContentResolver().query(
Uri.parse("content://call_log/calls"), projection,
selection, selectionArgs, sortOrder);
if (cursor != null) {
// Loop through the call log.
while (cursor.moveToNext()) {
// Common Call Log Items
String callNumber = cursor
.getString(cursor
.getColumnIndex(android.provider.CallLog.Calls.NUMBER));
setA.add(callNumber);
}
generateList();
}
} catch (Exception e) {
}
}
#SuppressLint("NewApi")
private void generateList() {
// TODO Auto-generated method stub
try {
Object[] calllist = new String[setA.size()];
calllist = setA.toArray();
String scalllist[] = Arrays.copyOf(calllist, calllist.length,
String[].class);
for (int i = 0; i < scalllist.length; i++) {
scalllist[i] = scalllist[i] + " "
+ getContactName(this, scalllist[i]);
}
final Dialog d = new Dialog(this);
d.setContentView(R.layout.dialog1);
d.setTitle("Choose from Call Log...");
final ListView lv1 = (ListView) d.findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1,
scalllist);
lv1.setAdapter(adapter);
lv1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
String clickednumber[] = (lv1.getItemAtPosition(arg2)
.toString()).split(" ");
usernumber.setText(clickednumber[0]);
try {
username.setText(clickednumber[1]);
} catch (ArrayIndexOutOfBoundsException e) {
username.setText(" ");
}
d.dismiss();
}
});
d.show();
} catch (Exception e) {
}
}
private String getContactName(Context context, String number) {
String name = null;
try {
// define the columns I want the query to return
String[] projection = new String[] {
ContactsContract.PhoneLookup.DISPLAY_NAME,
ContactsContract.PhoneLookup._ID };
// encode the phone number and build the filter URI
Uri contactUri = Uri.withAppendedPath(
ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(number));
// query time
Cursor cursor = context.getContentResolver().query(contactUri,
projection, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
name = cursor
.getString(cursor
.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
} else {
name = " ";
}
cursor.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return name;
}

Retrieving all contact id with length 4 android

I need to retrieve contacts Id with that have <=7 characters and add two 0's in front and update the contact list. How can i achieve this
public class MainActivity extends Activity {
public static final int PICK_CONTACT = 1;
Uri uri;
TextView txt_contacts;
Cursor c = null;
MainActivity context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
getContactList();
// this opens the activity. note the Intent.ACTION_GET_CONTENT
// and the intent.setType
((Button)findViewById(R.id.btn_contacts)).setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
// user BoD suggests using Intent.ACTION_PICK instead of .ACTION_GET_CONTENT to avoid the chooser
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, 1);
txt_contacts =(TextView)findViewById(R.id.txt_contacts);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
uri = data.getData();
if (uri != null) {
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone._ID },
null, null, null);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
int type = c.getInt(1);
showSelectedNumber(type, number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
public void showSelectedNumber(int type, String number) {
String new_num = 0+number;
/*
* QUERY TO UPDATE PHONE NUMBER
*/
ContentValues _changed_values=new ContentValues();
_changed_values.put(ContactsContract.CommonDataKinds.Phone.NUMBER,new_num);
getContentResolver().update(uri,_changed_values,
ContactsContract.CommonDataKinds.Phone._ID+"=?", new String[]{String.valueOf(type)});
txt_contacts.setText(new_num);
}
public List<Person> getContactList(){
ArrayList<Person> contactList = new ArrayList<Person>();
Uri contactUri = ContactsContract.Contacts.CONTENT_URI;
String[] PROJECTION = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER,
};
String SELECTION = "LENGTH(" + ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + ")>'7'";
Cursor contacts = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, PROJECTION, SELECTION, null, null);
if (contacts.getCount() > 0)
{
while(contacts.moveToNext()) {
Person aContact = new Person();
int idFieldColumnIndex = 0;
int nameFieldColumnIndex = 0;
int numberFieldColumnIndex = 0;
String contactId = contacts.getString(contacts.getColumnIndex(ContactsContract.Contacts._ID));
nameFieldColumnIndex = contacts.getColumnIndex(PhoneLookup.DISPLAY_NAME);
if (nameFieldColumnIndex > -1)
{
aContact.setName(contacts.getString(nameFieldColumnIndex));
}
PROJECTION = new String[] {Phone.NUMBER};
final Cursor phone = managedQuery(Phone.CONTENT_URI, PROJECTION, Data.CONTACT_ID + "=?", new String[]{String.valueOf(contactId)}, null);
if(phone.moveToFirst()) {
while(!phone.isAfterLast())
{
numberFieldColumnIndex = phone.getColumnIndex(Phone.NUMBER);
if (numberFieldColumnIndex > -1)
{
aContact.setPhoneNum(phone.getString(numberFieldColumnIndex));
phone.moveToNext();
TelephonyManager mTelephonyMgr;
mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (!mTelephonyMgr.getLine1Number().contains(aContact.getPhoneNum()))
{
contactList.add(aContact);
}
}
}
}
phone.close();
}
contacts.close();
}
return contactList;
}
You may want to take a look at this:
How to get contacts from native phonebook in android
For your case you should just have to change the SELECTION query statement to something like:
Uri contactUri = ContactsContract.Contacts.CONTENT_URI;
String[] PROJECTION = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
};
String SELECTION = "LENGTH(" + ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + ")<='4'";
Cursor contacts = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, PROJECTION, SELECTION, null, null);

Querying all phone numbers of a contact

I managed to write add program that upon the user click a button, he will be able to retrieve a phone number that will fill an editText box. The problem is that if a contact has multiple numbers, it will always take the top most number.
I have been reading another thread, Getting Number from Contacts Picker, there is an answer, but I don't get it. As I am new to android programming,
I'll appreciate if anyone out there could give me step by step instructions.
First, you may need to query all contact in phone book.
// Run query
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME
};
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '1'";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
// Build adapter with contact entries
Cursor mCursor = managedQuery(uri, projection, selection, selectionArgs, sortOrder);
//
// Bind mCursor to to your Listview
//
After that, when user select a contact in your list view, you make a second query to get label and number of that contact.
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
mCursor.moveToPosition(position);
startManagingCursor(mCursor);
String contactID = mCursor.getString(mCursor.getColumnIndex(ContactsContract.Contacts._ID));
Cursor phoneNumCursor = getContentResolver().query(Phone.CONTENT_URI,
null, Phone.CONTACT_ID + "=?", new String[] { contactID }, null);
phoneNumCursor.moveToFirst();
Vector<String> phoneTypeList = new Vector<String>();
Vector<String> phoneNumberList = new Vector<String>();
while (!phoneNumCursor.isAfterLast()){
int type = phoneNumCursor.getInt(phoneNumCursor.getColumnIndex(Phone.TYPE));
phoneTypeList.add(String.valueOf(Phone.getTypeLabel(getResources(),type,"")));
phoneNumberList.add(phoneNumCursor.getString(phoneNumCursor.getColumnIndex(Phone.NUMBER)));
phoneNumCursor.moveToNext();
}
//
// Feel free to show label and phone number of that contact. ^^
//
Updated:
Below is an example if you want to use Contact Picker.
private static final int CONTACT_PICKER_RESULT = 1001;
protected void startContactPicker(){
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,Contacts.CONTENT_URI);
startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
Cursor cursor = null;
String phoneNumber = "";
try {
Uri result = data.getData();
String id = result.getLastPathSegment();
cursor = getContentResolver().query(Phone.CONTENT_URI,
null, Phone.CONTACT_ID + "=?", new String[] { id }, null);
int phoneIdx = cursor.getColumnIndex(Phone.DATA);
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()){
phoneNumber = cursor.getString(phoneIdx);
//
// this will go through all phoneNumber of selected contact.
//
cursor.moveToNext();
}
}
} catch (Exception e) {
} finally {
if (cursor != null) {
cursor.close();
}
numberView.setText(phoneNumber);
}
break;
}
}
}

Multiple Contact Picker List [getCheckedItemPositions()]

Below is a my Contact_Picker class. I am going to be using this class to create a list of contacts with checkboxes, giving the user the option to select multiple contacts from their phonebook. I have a layout xml that I am using that has 2 buttons at the bottom: Clear All and Done.
When 'Done' is pressed, I need it to get all of the names that are checked, and save them in a list/preferences file. Right now, I can find what POSITIONS are checked, but I don't know how to retrieve the corresponding information associated with them (the name/phone number of the selected contact). I have searched for days on a method that will work, and have not come up with anything. Any code/pseudo code/ideas are greatly appreciated.
Contact_Picker Class:
public class Contact_Picker extends ListActivity {
protected static final String TAG = null;
public String[] Contacts = {};
public int[] to = {};
public ListView myListView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contacts_list);
final Button done_Button = (Button) findViewById(R.id.done_Button);
final Button clear_Button =(Button) findViewById(R.id.clear_Button);
Cursor mCursor = getContacts();
startManagingCursor(mCursor);
ListAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_multiple_choice, mCursor,
Contacts = new String[] {ContactsContract.Contacts.DISPLAY_NAME },
to = new int[] { android.R.id.text1 });
setListAdapter(adapter);
myListView = getListView();
myListView.setItemsCanFocus(false);
myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
clear_Button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"Selections Cleared", Toast.LENGTH_SHORT).show();
ClearSelections();
}
});
/** When 'Done' Button Pushed: **/
done_Button.setOnClickListener(new View.OnClickListener() {
public void onClick (View v){
Log.i(TAG,":Done Button Selected:");
SparseBooleanArray checkedPositions = myListView.getCheckedItemPositions();
Log.i(TAG,"Number of Checked Positions: " + checkedPositions.size());
if (checkedPositions != null)
{
int count = myListView.getCount();
for ( int i=0;i<count;i++)
{
Log.i(TAG,"Selected items: " + checkedPositions.get(i));
}
}
}
}); //<-- End of Done_Button
} //<-- end of onCreate();
private void ClearSelections() {
int count = this.myListView.getAdapter().getCount();
for (int i = 0; i < count; i++) {
this.myListView.setItemChecked(i, false);
}
}
private Cursor getContacts() {
// Run query
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME };
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '"
+ ("1") + "'";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
return managedQuery(uri, projection, selection, selectionArgs,
sortOrder);
} //<-- end of getContacts();
}
Will Create Output Such As:
Sele02-12 01:25:09.733: INFO/(219): :Done Button Selected:
02-12 01:25:09.743: INFO/(219): Number of Checked Positions: 2
02-12 01:25:09.743: INFO/(219): Selected items: true
02-12 01:25:09.743: INFO/(219): Selected items: false
02-12 01:25:09.743: INFO/(219): Selected items: true
02-12 01:25:09.752: INFO/(219): Selected items: false
see this
public String[] getlistcontacts() {
// TODO Auto-generated method stub
int i=0;
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null,null, null, null);
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null , null);
int a= cur.getCount();
String[] cttlist=new String[a+1];
cur.moveToFirst();
pCur.moveToFirst();
for (int j=0; j<a;j++){
int nm=cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
//int nb=pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String name=cur.getString(nm);
int nb=pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String number=pCur.getString(nb);
cttlist[i]=name.concat("<;>").concat(number);
//Toast.makeText(PizzastimeActivity.this, "alkamkljziha"+name+":"+number, Toast.LENGTH_LONG).show();
i++;
cur.moveToNext();
pCur.moveToNext();
}
return cttlist;
}
in this code i tried to get list of contact in a table of string then u can use it easily
Here is a correct approach:
SparseBooleanArray selectedPositions = listView.getCheckedItemPositions();
for (int i=0; i<selectedPositions.size(); i++) {
if (selectedPositions.get(selectedPositions.keyAt(i)) == true) {
//do stuff
}
}
maybe you can manually keep track of your contacts:
Vector<String> names=new Vector<String>();
private Cursor getContacts() {...
Cursor cur = managedQuery(uri, projection, selection, selectionArgs,
sortOrder);
int col = cur.getColumnIndex("display_name");
while(cur.moveToNext())
names.add(cur.getString(col));
cur.moveToFirst();
return cur;
}
and then output them synchronously:
for ( int i=0;i<count;i++)
{
Log.i(TAG,"Selected items: " + checkedPositions.get(i));
Log.i(TAG,"Selected name: " + names.get(i));
}
I forgot about this post until Team Pannous left an answer. I'm sure that their method would work, but I ended up using this instead:
SparseBooleanArray checked = myListView.getCheckedItemPositions();
for (int i = 0; i < ContactsList.length; i++) {
Log.v(TAG, ContactsList[i] + ": " + checked.get(i)); //<-- Will print every contact with 'true'
if (checked.get(i) == true) {
Object o = getListAdapter().getItem(i);
String name = o.toString();
WriteSettings(self, name);
}
}
Just in case anyone else is having a problem with a multiple-choice listview.

Categories

Resources