2

I have a contact picker list with chckboxes of the contacts that have a phone number. Now, my problem is that can't seem to get the checked contact's name and phone number.

Here is my code:

    import android.app.ListActivity;
    import android.content.ContentResolver;
    import android.content.Intent;
    import android.database.Cursor;
    import android.net.Uri;
    import android.os.Bundle;
    import android.provider.ContactsContract;
    import android.provider.ContactsContract.CommonDataKinds.Phone;
    import android.util.Log;
    import android.util.SparseBooleanArray;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ListAdapter;
    import android.widget.ListView;
    import android.widget.SimpleCursorAdapter;

    public class Create_Group extends ListActivity implements OnClickListener{

        // List variables
        public String[] Contacts = {};
        public int[] to = {};
        public ListView myListView;

        Button save_button;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.create_group);

            // Initializing the buttons according to their ID
            save_button = (Button)findViewById(R.id.save_group_button);

            // 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.save_group_button:

                int checked_Names_Counter = 0;

                // Goes over the list of contacts and checks which were checked
                for (int j = 0; j < myListView.getCount(); j++)
                {
                    if (myListView.isItemChecked(j) == true)
                    {   
                        Cursor cur = getContacts();
                        ContentResolver contect_resolver = getContentResolver();
                        cur.moveToFirst();

                        /**
                        * Here I tried to compare the IDs but each list has different IDs so it didn't really help me...
                        // Converts the current checked name ID into a String
                        String Checked_ID = String.valueOf(myListView.getCheckedItemIds()[checked_Names_Counter]);

                        // Checks if the current checked ID matches the cursors ID, if not move the cursor to the next name
                        while (Checked_ID != cur.getString(cur.getColumnIndexOrThrow(ContactsContract.Contacts._ID)))
                        {
                            cur.moveToNext();
                        }
                        */

                        /**
                        * Here I tried to compare the names, even though it's not a good pratice, and it didn't work either...
                        String Checked_Name = myListView.getAdapter().getItem(checked_Names_Counter).toString();

                        // Checks if the current checked ID matches the cursors ID, if not move the cursor to the next name
                        while (Checked_Name != cur.getString(cur.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)))
                        {
                            cur.moveToNext();
                        }
                        */
                        String id = cur.getString(cur.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
                        String name = "";
                        String no = "";

                        Cursor phoneCur = contect_resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null);


                        name = phoneCur.getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                        no = phoneCur.getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                        id = null;
                        name = null;
                        no = null;
                        phoneCur = null;
                        checked_Names_Counter++;

                    }
                }

                // Goes back to the Manage Groups screen
                i = new Intent(this, Manage_Groups.class);
                startActivity(i);
                break;  
        }

      }
    }

Any ideas?

Thanks!!

user1476876
  • 65
  • 2
  • 12

1 Answers1

2

It looks like you are so close, I used ListView.getCheckedItemIds() to return unique ids of the selected contacts:

public void onClick(View view) {
    long[] ids = myListView.getCheckedItemIds();
    for(long id : ids) {
        Cursor contact = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, 
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id + "" }, null);

        // Do whatever you want with the data
    }
}

Addition

I have a quick question about this code:

// Goes back to the Manage Groups screen
i = new Intent(this, Manage_Groups.class);
startActivity(i);

Does this bring the user back to a previous Activity? If so you should use finish(); instead. finish() ends the current Activity, taking it off the stack and freeing up any memory (less memory wasted means a faster app.) It also allows the previous Activity to restore the saved state when it left (filled in EditTexts, previous Spinner selections, toggle button and checkmarks, etc.) The Activity resumes where the user left off.

Sam
  • 86,580
  • 20
  • 181
  • 179
  • Yes, it does go back to a previous Activity, and I'll add what you said. Plus, I only checked what you posted briefly, but I think it works great, I'll finish checking it later. Thanks!!! – user1476876 Jul 01 '12 at 17:43
  • @user1476876 If this answer helped you please click the checkmark in the upper-left corner. – Sam Jul 01 '12 at 19:08
  • 2
    As a warning for others seeing this answer. You shouldn't call ContentResolver.query on the main thread. You risk getting an ANR since the call will perform file IO. Load the contacts in a Loader or AsyncTask or similar. You could also edit the query to load all the relevant contacts in one query in stead of one query per contact. – Martin Wallgren Dec 28 '13 at 12:17