Search code examples
androidandroid-studiocontacts

Get and select contacts in android


I'm trying get all contacts and select it.

I completed get all contacts in my phone. But when i try to select a few contacts and get their names or numbers, I faced nullpointer error.

public class ContactListFragment extends ListFragment implements LoaderCallbacks<Cursor> {

private CursorAdapter mAdapter;
final HashMap<String,String> hashMap = new HashMap<String,String>();
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
private Uri uriContact;

private String contactID;
String[] projection    = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
        ContactsContract.CommonDataKinds.Phone.NUMBER};


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // create adapter once
    Context context = getActivity();
    int layout = android.R.layout.simple_list_item_multiple_choice;
    Cursor c = null; // there is no cursor yet
    int flags = 0; // no auto-requery! Loader requeries.
    mAdapter = new SimpleCursorAdapter(context, layout, c, FROM, TO, flags);
}



@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    // each time we are started use our listadapter
    setListAdapter(mAdapter);
    getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

    // and tell loader manager to start loading
    getLoaderManager().initLoader(0, null, this);

    ***getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Cursor cursorID = getActivity().getContentResolver().query(uriContact,
                    new String[]{ContactsContract.Contacts._ID},
                    null, null, null);
            contactID = cursorID.getString(cursorID.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            System.out.println(contactID);
        }
    });
}***

// columns requested from the database
private static final String[] PROJECTION = {
        Contacts._ID, // _ID is always required
        Contacts.DISPLAY_NAME_PRIMARY // that's what we want to display
};

// and name should be displayed in the text1 textview in item layout
private static final String[] FROM = { Contacts.DISPLAY_NAME_PRIMARY };
private static final int[] TO = { android.R.id.text1 };

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {

    // load from the "Contacts table"
    Uri contentUri = Contacts.CONTENT_URI;

    // no sub-selection, no sort order, simply every row
    // projection says we want just the _id and the name column
    return new CursorLoader(getActivity(),
            contentUri,
            PROJECTION,
            null,
            null,
            null);
}

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    // Once cursor is loaded, give it to adapter
    mAdapter.swapCursor(data);

}

@Override
public void onLoaderReset(Loader<Cursor> loader) {
    // on reset take any old cursor away
    mAdapter.swapCursor(null);
}

I think problem is my onItemClickListener.

How can i fix this? Thanks from now :)


Solution

  • The main problem is that uriContact is null when you make the query.

    The other problem is that you are only using ContactsContract.Contacts._ID as the projection, so the ID is the only thing returned.

    I got it working by using null for the projection so that it returns all rows.

    I also added functionality to find the currently selected contact, and display a Toast with their phone number.

    This is not optimal code, since it just queries all rows and then iterates through them until it finds the currently selected contact, but it works:

      getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Cursor cur = mAdapter.getCursor();
                cur.moveToPosition(position);
                String curName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY));
                System.out.println(curName);
                uriContact = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
                Cursor cursorID = getContentResolver().query(uriContact,
                        null,
                        null, null, null);
                for (cursorID.moveToFirst(); !cursorID.isAfterLast(); cursorID.moveToNext() ) {
                    String testName = cursorID.getString(cursorID.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY));
                    if (testName != null && testName.equals(curName)) {
                        contactID = cursorID.getString(cursorID.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    }
                }
                if (contactID != null) {
                    System.out.println(contactID);
                    Toast.makeText(MainActivity.this, "contact Phone: " + contactID, Toast.LENGTH_LONG).show();
                }
            }
        });
    

    Edit: I got a more optimized version working, which uses the selection and selectionArgs in the query to return just the current contact info:

      getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Cursor cur = mAdapter.getCursor();
                cur.moveToPosition(position);
                String curName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY));
                System.out.println(curName);
                uriContact = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
                Cursor cursorID = getContentResolver().query(uriContact,
                        null,
                        ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + " = ?", new String[]{curName}, null);
                if (cursorID.moveToFirst()) {
                    contactID = cursorID.getString(cursorID.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                }
                if (contactID != null) {
                    System.out.println(contactID);
                    Toast.makeText(MainActivity.this, "contact Phone: " + contactID, Toast.LENGTH_LONG).show();
                }
            }
        });