检索短信详细信息时未显示姓名?

时间:2012-07-12 12:14:31

标签: android

我正在使用2.1平台我可以使用下面的代码检索短信详细信息。但是只显示数字和短信主体,名称还没有到来,我还能做什么来检索姓名?

public class SMSActivity extends Activity {

    ListView lview;
    String Body  = "" ; 
    ArrayList<String> smslist=new ArrayList<String>();
    ArrayAdapter<String> itemAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main);
    lview =(ListView)findViewById(R.id.lv);
    itemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,smslist);
    lview.setAdapter(itemAdapter);

    ContentResolver cr = getContentResolver();
    Cursor c = getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);
    while(c.moveToNext()){

    Number = c.getString(c.getColumnIndexOrThrow("address"));

   Body = c.getString(c.getColumnIndexOrThrow("body")).toString();

   smslist.add( Number + ":" +"\n"+ Body);
    }
    itemAdapter.notifyDataSetChanged();

    c.close();
}
} 

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

你有数字吧!!现在将此号码传递给此方法,它将返回相应号码的联系人姓名。

   public String getContactName(String number) {
        String cName = null;
        Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
        String nameColumn[] = new String[]{PhoneLookup.DISPLAY_NAME};
        Cursor c =  getContentResolver().query(uri, nameColumn, null, null, null);
        if(c == null || c.getCount() == 0)
            return cName;
        c.moveToFirst();
        cName = c.getString(0);
        return cName;

    }

添加以下权限

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

在您的清单文件中

Read_contact数据。

代码替换此代码

Number = c.getString(c.getColumnIndexOrThrow("address"));

   Body = c.getString(c.getColumnIndexOrThrow("body")).toString();

   smslist.add( Number + ":" +"\n"+ Body);

以下

   Number = c.getString(c.getColumnIndexOrThrow("address"));
   String name = getContactName(Number); // declare name outside

   Body = c.getString(c.getColumnIndexOrThrow("body")).toString();
  if( name == null )
     smslist.add( Number + ":" +"\n"+ Body);
  else
        smslist.add( name + ":" +"\n"+ Body);