17

I am new to android.When i try to get contact names its working fine but i want to get numbers only, but i am not able to do so. My code is:-

package com.example.sqllitecontactlist;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class PhoneBookActivity extends Activity {

//Android listview object
ListView listViewPhoneBook;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
  setContentView(R.layout.phone_book);

   //get the ListView Reference from xml file
  listViewPhoneBook=(ListView)findViewById(R.id.listPhoneBook);
  String[] arrayColumns = new String[]{ ContactsContract.CommonDataKinds.Phone.NUMBER};

    // arrayViewID is the id of the view it will map to here textViewPhone only 
  int[] arrayViewID = new int[]{R.id.textViewNumber};

 Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,        arrayColumns, null, null, null);

SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.each_contact,    cursor, arrayColumns, arrayViewID);
 listViewPhoneBook.setAdapter(adapter); }}

When i execute this it says "java.lang.IllegalArgumentException: Invalid column data1". i have googled it a lot and applied some solution but failed. Please help me out

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
Arpit Sethi
  • 173
  • 1
  • 1
  • 4
  • Added simple library to fetch contacts with [example and source code available here](https://github.com/nitiwari-dev/android-contact-extractor) – Nitesh Tiwari May 12 '17 at 10:00

4 Answers4

32
    getNumber(this.getContentResolver()); 


public void getNumber(ContentResolver cr)
{
    Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
            // use the cursor to access the contacts    
    while (phones.moveToNext())
    {
      String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
             // get display name
      phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
              // get phone number
      System.out.println(".................."+phoneNumber); 
    }

}

activity_main.xml

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context=".MainActivity" >

<ListView
   android:layout_width="match_parent"
   android:layout_height="fill_parent"
   android:id="@+id/lv"/>

</RelativeLayout>

MainActivity.java

 public class MainActivity extends Activity {

     String phoneNumber;
     ListView lv;
     ArrayList <String> aa= new ArrayList<String>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
         lv= (ListView) findViewById(R.id.lv);

        getNumber(this.getContentResolver()); 
    }

    public void getNumber(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));
          phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
          System.out.println(".................."+phoneNumber); 
          aa.add(phoneNumber);
        }
                 phones.close()// close cursor
          ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_1,aa);
          lv.setAdapter(adapter);
                  //display contact numbers in the list
    }
      }

snap shot

enter image description here

Make sure you have this in manifest

       <uses-permission android:name="android.permission.READ_CONTACTS"/>
AndyN
  • 1,742
  • 1
  • 15
  • 30
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • :- done... can u pls tell me cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null); in the second parameter we are passing null, what does it mean..By doing this it fetches all the columns? – Arpit Sethi May 24 '13 at 10:15
  • @ArpitSethi it fetches all the contacts and in the list you will see all the numbers from your contacts list – Raghunandan May 24 '13 at 10:20
  • @ArpitSethi for clarity http://developer.android.com/reference/android/content/ContentResolver.html. scroll down and check the query method and its parameters – Raghunandan May 24 '13 at 10:21
  • @ArpitSethi you can specify the column you want in the above it queries all columns which is not efficient. specify the column you need and keep the rest the same – Raghunandan May 24 '13 at 10:26
  • @ArpitSethi check this link for clarity http://stackoverflow.com/questions/6587674/android-contacts-display-name-and-phone-numbers-in-single-database-query – Raghunandan May 24 '13 at 10:27
  • u are really a very helpful hand... :) – Arpit Sethi May 24 '13 at 10:31
  • Well done for having an example that actually compiles first time. – Captain Kenpachi Oct 14 '16 at 11:56
  • @JuannStrauss thank you. But you should use loaders instead of the approach i mentioned here. That's more correct way of doing things. Besides reading from database can be done on a background thread. Loaders are the best way.. – Raghunandan Oct 14 '16 at 11:57
9

My solution to recover all contacts:

    Cursor cursor = null;
    try {
        cursor = context.getContentResolver().query(Phone.CONTENT_URI, null, null, null, null);
        int contactIdIdx = cursor.getColumnIndex(Phone._ID);
        int nameIdx = cursor.getColumnIndex(Phone.DISPLAY_NAME);
        int phoneNumberIdx = cursor.getColumnIndex(Phone.NUMBER);
        int photoIdIdx = cursor.getColumnIndex(Phone.PHOTO_ID);
        cursor.moveToFirst();
        do {
            String idContact = cursor.getString(contactIdIdx);
            String name = cursor.getString(nameIdx);
            String phoneNumber = cursor.getString(phoneNumberIdx);
            //...
        } while (cursor.moveToNext());  
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

You need this permission in your manifest :

<uses-permission android:name="android.permission.READ_CONTACTS" />

I hope I have helped you!

lopez.mikhael
  • 9,943
  • 19
  • 67
  • 110
3

.@Arpit:

add the permission in your manifest.

BUT MOST IMPORTANTLY... Didn't you noticed that just below the line where you formatted the phoneNumber you did not add the names? You should add the name to the number just the way you added the phoneNumber (I enclosed in the code below):

..System.out.println(".................."+phoneNumber); 
aa.add(name);
aa.add(phoneNumber);

the output of the above code will be separate names and numbers on your listview(like this):


name

number

name

in order to display that in one line, you can do this:

aa.add(name+"\n"+phoneNumber);

and the output will be like this:


name number


name number


name number


good luck!

Gojin
  • 31
  • 3
0

Find the solution below, It will work for getting contact no from contactlist.

You need permission like:

 android:name="android.permission.READ_CONTACTS"/>

Then, Calling the Contact Picker:

 Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);

Then,

 @Override
 public void onActivityResult(int reqCode, int resultCode, Intent data) {
 super.onActivityResult(reqCode, resultCode, data);

 switch (reqCode) {
  case (PICK_CONTACT) :
   if (resultCode == Activity.RESULT_OK) {
    Uri contactData = data.getData();
    Cursor c =  managedQuery(contactData, null, null, null, null);
     if (c.moveToFirst()) {
      String name = c.getString(c.getColumnIndexOrThrow(People.NAME));
      // TODO Whatever you want to do with the selected contact name.
    }
  }
  break;
  }
 }
Paresh Mayani
  • 127,700
  • 71
  • 241
  • 295
Rakesh
  • 2,732
  • 29
  • 28