簡體   English   中英

在Android OS上檢索聯系人

[英]Retrieve contacts on Android OS

我試圖使用此代碼段來檢索一個接一個的聯系人。 信息:我已設置權限<uses-permission android:name="android.permission.READ_CONTACTS"/>

    Context context = getActivity();
    Cursor cursor = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, new String[]{Phone.NUMBER}, null, null, null);

    while (cursor.moveToNext()) {
        String number = cursor.getString(cursor.getColumnIndex(Phone.NUMBER));
        Log.i("Number: ", number);
    }
    cursor.close();

這就是我的StackTrace給出的內容,我不太理解它的含義:

Pick [Android Application]  
<terminated>Pick [Android Application]  
<disconnected>DalvikVM [localhost:8600] 
Pick [Android Application]  
DalvikVM [localhost:8600]   
    Thread [<1> main] (Suspended (exception IllegalArgumentException))  
        <VM does not provide monitor information>   
        ContextImpl$ApplicationContentResolver(ContentResolver).query(Uri, String[], String, String[], String, CancellationSignal) line: 458    
        ContextImpl$ApplicationContentResolver(ContentResolver).query(Uri, String[], String, String[], String) line: 360    
        FragmentContacts.onCreateView(LayoutInflater, ViewGroup, Bundle) line: 21   
        FragmentContacts(Fragment).performCreateView(LayoutInflater, ViewGroup, Bundle) line: 1500  
        FragmentManagerImpl.moveToState(Fragment, int, int, int, boolean) line: 927 
        FragmentManagerImpl.moveToState(int, int, int, boolean) line: 1104  
        BackStackRecord.run() line: 682 
        FragmentManagerImpl.execPendingActions() line: 1467 
        FragmentManagerImpl$1.run() line: 440   
        Handler.handleCallback(Message) line: 730   
        FragmentActivity$1(Handler).dispatchMessage(Message) line: 92   
        Looper.loop() line: 137 
        ActivityThread.main(String[]) line: 5419    
        Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]  
        Method.invoke(Object, Object...) line: 525  
        ZygoteInit$MethodAndArgsCaller.run() line: 1187 
        ZygoteInit.main(String[]) line: 1003    
        NativeStart.main(String[]) line: not available [native method]  
    Thread [<10> Binder_2] (Running)    
    Thread [<9> Binder_1] (Running) 
    Daemon Thread [<11> RefQueueWorker@org.apache.http.impl.conn.tsccm.ConnPoolByRoute@42a6b128] (Running)  
    Thread [<14> pool-3-thread-1] (Running) 
    Thread [<15> ParseCommandCache.runLoop()] (Running) 

那是因為您試圖獲取查詢時未請求的列數據。 將您的查詢行更改為此:

Cursor cursor = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, new String[]{Phone.NUMBER}, null, null, null);

對於要從​​中讀取數據的每一列,請確保也將其包括在投影數組中。 query()方法的第二個參數是一個String數組,其中包含您感興趣的列。

更好的方法是這樣的:

// columns we're interested in reading data from
String[] projection = {Phone.NUMBER, OTHER_COLUMNS};

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

閱讀本教程以獲取更多信息: http : //developer.android.com/training/load-data-background/index.html

更新:您不能直接從聯系人表中獲取電話號碼。 由於聯系人可以有多個號碼,因此它們存儲在不同的表中。

為此,我們將不得不使用嵌套的游標查詢。 運作方式如下:

  1. ContactsContract.Contacts._ID添加到您的投影數組。 此ID字段包含每個聯系人的聯系人ID。

  2. 遍歷您的光標,並為每個聯系人ID獲取其電話號碼。

這是詳細的解決方案:

    // uri for the contacts data
    Uri contactsUri = ContactsContract.Contacts.CONTENT_URI;

    // columns we're interested in
    String[] projection = new String[] {
            ContactsContract.Contacts._ID,
            ContactsContract.Contacts.DISPLAY_NAME,
    };

    // we do not want contacts who do not have phone numbers
    // so we'll only query contacts whose phone numbers count is > 0
    String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + " >? ";
    String[] selectionArgs = new String[] {"0"};

    // query all contacts
    Cursor cursor = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, projection, selection, selectionArgs, null);

    // this list will hold lists of phone numbers of all contacts
    ArrayList<ArrayList<String>> allContactNumbers = new ArrayList<ArrayList<String>>();

    if(cursor != null){
        try{

            // for each contact Id, we'll fetch his numbers
            while(cursor.moveToNext()){

                  // get his contactId
                  String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID))

                  // ArrayList that will hold his phone numbers
                  ArrayList<String> phoneNumbers = new ArrayList<String>();

                  Cursor numberCursor = contResv.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", new String[]{ contactId }, null);

                  try{

                          // add each phone number to phoneNumbers
                          while (numberCursor.moveToNext()){
                                 String contactNumber = numberCursor.getString(numberCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                                 phoneNumbers.add(contactNumber);
                          }

                  }finally{
                          numberCursor.close();
                  }  

                  // and add each contact's phone numbers to our master list
                  allContactNumbers.add(phoneNumbers);

        }finally{

         // close the cursor when we're done using it to avoid any database leaks
         cursor.close();
        }
    }

    // now do whatever you want with allContactNumbers.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM