2011-01-06 14 views
9

Sto cercando di recuperare l'elenco dei contatti con il loro nome e numero di telefono. Provo seguente codice:Come recuperare il nome e il numero di telefono del contatto in Android

// Get a cursor over every contact. 
    Cursor cursor = getContentResolver().query(People.CONTENT_URI, 
               null, null, null, null); 
    // Let the activity manage the cursor lifecycle. 
    startManagingCursor(cursor); 
    // Use the convenience properties to get the index of the columns 
    int nameIdx = cursor.getColumnIndexOrThrow(People.NAME); 

    int phoneIdx = cursor. getColumnIndexOrThrow(People.NUMBER); 
    String[] result = new String[cursor.getCount()]; 
    if (cursor.moveToFirst()) 
     do { 
     // Extract the name. 
     String name = cursor.getString(nameIdx); 
     // Extract the phone number. 
     String phone = cursor.getString(phoneIdx); 
     result[cursor.getPosition()] = name + "-" +" "+ phone; 
     } while(cursor.moveToNext()); 

Questo codice dovrebbe restituire un array con il nome di tutti i contatti e il suo numero di telefono, ma questo nome solo rendimenti del contatto e restituisce NULL nel numero di telefono,

Esempio di output:

John - null 
+0

Al momento non riesco a emulare il tuo problema, ma mi piace chiedere qual è il numero di telefono che stai ricevendo? Hai controllato nel database di contatto se questi campi sono presenti? – sat

risposta

3

non utilizzare l'accesso API deprecato come come seguire

 Cursor cursor = getContentResolver(). 
    query(Contacts.CONTENT_URI, 
      new String[]{Contacts.DISPLAY_NAME}, null, null,null); 
    if(cursor!=null){ 
     while(cursor.moveToNext()){ 
      Cursor c = getContentResolver().query(Phone.CONTENT_URI, new String[]{Phone.NUMBER, Phone.TYPE}, 
        " DISPLAY_NAME = '"+cursor.getString(cursor.getColumnIndex(Contacts.DISPLAY_NAME))+"'", null, null); 
      while(c.moveToNext()){ 
       switch(c.getInt(c.getColumnIndex(Phone.TYPE))){ 
       case Phone.TYPE_MOBILE : 
       case Phone.TYPE_HOME : 
       case Phone.TYPE_WORK : 
       case Phone.TYPE_OTHER : 
       } 
      } 
     } 
    } 
+0

Come si legge effettivamente un numero di telefono? Quando eseguo 'String phone = Phone.NUMBER', restituisce' data1' – learner

0

H ellBoy ha ragione, Phone.xxx è privato. L'ho fatto in questo modo, con una ricerca-uri:

Uri look = Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, "23N9983726428fnwe"); 
Intent i = new Intent(Intent.ACTION_VIEW); 
i.setData(look); 

Esperimento con Contacts.xxx in prima linea, si trova il sollution destra.

1

guardare il codice di esempio per recuperare i contatti da cellulare Android,

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


String contactId = cursor.getString(cursor 
        .getColumnIndex(ContactsContract.Contacts._ID)); 

String name = cursor.getString(cursor     .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); 

      Cursor phones = context.getContentResolver().query(
        Phone.CONTENT_URI, null, 
        Phone.CONTACT_ID + " = " + contactId, null, null); 
      while (phones.moveToNext()) { 
       String number = phones.getString(phones 
         .getColumnIndex(Phone.NUMBER)); 
       int type = phones.getInt(phones.getColumnIndex(Phone.TYPE)); 
       switch (type) { 
       case Phone.TYPE_HOME:     
        Log.i("TYPE_HOME", "" + number); 
        break; 
       case Phone.TYPE_MOBILE:     
        Log.i("TYPE_MOBILE", "" + number); 
        break; 
       case Phone.TYPE_WORK:     
        Log.i("TYPE_WORK", "" + number); 
        break; 
       case Phone.TYPE_FAX_WORK:     
        Log.i("TYPE_FAX_WORK", "" + number); 
        break; 
       case Phone.TYPE_FAX_HOME: 
        Log.i("TYPE_FAX_HOME", "" + number); 
        break; 

       case Phone.TYPE_OTHER: 
        Log.i("TYPE_OTHER", "" + number); 
        break; 
       } 
      } 
      phones.close(); 
cursor.close(); 
0

provare il codice qui sotto.

Cursor managedCursor = getContentResolver() 
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
new String[] {Phone._ID, Phone.DISPLAY_NAME, Phone.NUMBER}, null, null, Phone.DISPLAY_NAME + " ASC"); 
10

In manifest Android:

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

Poi nell'attività:

editText.setOnFocusChangeListener(new OnFocusChangeListener(){ 

      @Override 
      public void onFocusChange(View v, boolean hasFocus) { 
       if(hasFocus){ 
        editText.setText(""); 
        Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI); 
        startActivityForResult(intent, PICK_CONTACT); 
       } 
      }   
     }); 

E poi devi prendere il risultato del contatto dell'azione di prelievo:

@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 id = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID)); 

        String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)); 

        if (hasPhone.equalsIgnoreCase("1")) 
        { 
         Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null, 
          ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id,null, null); 
         phones.moveToFirst(); 
         String cNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); 
         Toast.makeText(getApplicationContext(), cNumber, Toast.LENGTH_SHORT).show(); 

         String nameContact = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)); 

         editText.setText(nameContact+ " "+ cNumber); 
        } 
      } 
     } 
    } 
} 
+1

se un contatto contiene più di un numero, quindi come selezionare il numero desiderato. –

+0

Come userò 'PICK_CONTACT' – Si8

+0

creare una variabile globale" PICK_CONTACT ": int PICK_CONTACT = 10; – chemalarrea

0
package com.number.contatcs; 

import android.app.Activity; 

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.view.View; 

import android.widget.Button; 

import android.widget.EditText; 

public class Main2Activity extends Activity { 

private static final int CONTACT_PICKER_RESULT = 1001; 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main2); 
    Button getContacts = (Button) findViewById(R.id.button1); 
    getContacts.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      Intent i = new Intent(Intent.ACTION_PICK, 
        ContactsContract.CommonDataKinds.Phone.CONTENT_URI); 
      startActivityForResult(i, CONTACT_PICKER_RESULT); 

     } 
    }); 
} 

protected void onActivityResult(int reqCode, int resultCode, Intent data) { 
    super.onActivityResult(reqCode, resultCode, data); 
    if (resultCode == RESULT_OK) { 
     switch (reqCode) { 
     case CONTACT_PICKER_RESULT: 
      Cursor cursor = null; 
      String number = ""; 
      String lastName = ""; 
      try { 

       Uri result = data.getData(); 

       // get the id from the uri 
       String id = result.getLastPathSegment(); 

       // query 
       cursor = getContentResolver().query(
         ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
         null, 
         ContactsContract.CommonDataKinds.Phone._ID 
           + " = ? ", new String[] { id }, null); 

       // cursor = getContentResolver().query(Phone.CONTENT_URI, 
       // null, Phone.CONTACT_ID + "=?", new String[] { id }, 
       // null); 

       int numberIdx = cursor.getColumnIndex(Phone.DATA); 

       if (cursor.moveToFirst()) { 
        number = cursor.getString(numberIdx); 
        // lastName = 
        // cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME)); 
       } else { 
        // WE FAILED 
       } 
      } catch (Exception e) { 
       // failed 
      } finally { 
       if (cursor != null) { 
        cursor.close(); 
       } else { 
       } 
      } 
      EditText numberEditText = (EditText) findViewById(R.id.w); 
      numberEditText.setText(number); 
      // EditText lastNameEditText = 
      // (EditText)findViewById(R.id.last_name); 
      // lastNameEditText.setText(lastName); 

     } 

    } 
} 
} 
Problemi correlati