2017-06-02 135 views
0

我正在處理短信應用程序,我需要顯示SMS發件人的姓名。 例如,如果有人發送消息,應用程序將從電話簿中檢查其名稱,並顯示它是否不存在,然後顯示空字符串或空字符串。 我嘗試了一些代碼,但無法獲得,這是錯誤的。從電話簿獲取聯繫人姓名使用號碼 - Android

Exception smsReceiverandroid.database.CursorIndexOutOfBoundsException: After last row. 

這裏是代碼:

String displayName=""; 
       //Resolving the contact name from the contacts. 
       Uri lookupUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(senderNum)); 
       Cursor c = context.getContentResolver().query(lookupUri, new String[]{ContactsContract.Data.DISPLAY_NAME},null,null,null); 
       try { 
        c.moveToFirst(); 
        displayName = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); 
        //displayName = c.getString(0); 
        String ContactName = displayName; 
        Log.i("com.azeem.Debug", displayName); 
        Log.i("com.azeem.Debug", ContactName); 
        Toast.makeText(context, ContactName, Toast.LENGTH_LONG).show(); 

       } catch (Exception e) { 
        Log.e("SmsReceiver", "Exception smsReceiver" +e); 
       }finally{ 
        c.close(); 
       } 

senderNum是一個數字,人誰正在發送短信。 您能否讓我知道有關錯誤,看起來我試圖訪問index,這是不可用,但我能做些什麼來獲得聯繫人名稱

+0

請點擊此鏈接:HTTPS://developer.android.com/training/contacts-provider/retrieve-names.html#NameMatch – ashish

+0

我想你應該檢查光標的大小... –

回答

1

我檢查了你的代碼它工作正常。你需要在得到任何東西之前檢查你的cursor
這是我的代碼檢查了這一點。

Uri lookupUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(senderNum)); 
Cursor c = context.getContentResolver().query(lookupUri, new String[]{ContactsContract.Data.DISPLAY_NAME},null,null,null); 
try { 
    if(c.moveToFirst()) { 
     displayName = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); 
     //displayName = c.getString(0); 
     String ContactName = displayName; 
     Log.i("com.azeem.Debug", displayName); 
     Log.i("com.azeem.Debug", ContactName); 
     Toast.makeText(context, ContactName, Toast.LENGTH_LONG).show(); 
    } 
} catch (Exception e) { 
    e.printStackTrace(); 
}finally{ 
    c.close(); 
} 
相關問題