我正在开发一个SMS应用程序,希望在MainActivity中显示联系人姓名,我正在使用:
Uri uriSMSURI = Uri.parse("content://mms-sms/conversations?simple=true");
as
Uri uriSMSURI = Uri.parse("content://mms-sms/conversations");
在三星设备中抛出null异常。
代码:
//Log.v(LOGTAG, "Trying to get messgaes");
ContentResolver contentResolver = getContentResolver();
final String[] projection = new String[]{"*"};
//Log.v(LOGTAG, "Linking to mesages");
//Uri uriSMSURI = Uri.parse("content://sms/inbox");
//Uri uriSMSURI = Uri.parse("content://sms/sent");
Uri uriSMSURI = Uri.parse("content://mms-sms/conversations?simple=true");
//Log.v(LOGTAG, "Executing cursor");
Cursor cur = contentResolver.query(uriSMSURI, projection, null, null, "date DESC limit 10");
//Log.v(LOGTAG, "Messages query executed");
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex("_id"));
String recipient_id = cur.getString(cur.getColumnIndex("recipient_ids"));
Integer message_count = cur.getInt(cur.getColumnIndex("message_count"));
String address = cur.getString(cur.getColumnIndex("_id"));
final String body = cur.getString(cur.getColumnIndexOrThrow("snippet"));
final String date = cur.getString(cur.getColumnIndex("date"));
final Long timestamp = Long.parseLong(date);
//Log.v(LOGTAG, "Msg: " + body + " from: " + address);
address = address.trim();
String addressOriginal;
if (address.toString().startsWith("92")) {
address = address.toString().replace("92", "0");
} else if (address.toString().startsWith("3")) {
address = "0" + address;
} else if (address.toString().startsWith("+92")) {
address = address.toString().replace("+92", "0");
}
final String nAdd = address;
time = DateFormat.is24HourFormat(getApplicationContext());
if (time) {
dateFormat = new SimpleDateFormat("dd/MM/yyyy k:mm");
} else {
dateFormat = new SimpleDateFormat("dd/MM/yyyy h:mm a");
}
//String usr = getContactName(getApplicationContext(), nAdd);
Messages msg = new Messages();
msg.setThreadID(id);
msg.setRecipientID(recipient_id);
msg.setMessageCount(message_count);
msg.setMessage(body);
msg.setAddress(address);
msg.setTime(dateFormat.format(timestamp));
msg.setTimeStamp(timestamp);
String num = GetContactData(recipient_id); //Returns wrong number
msg.setSenderName(num);
msgList.add(msg);
}
return "done";
GetContactData函数:
public String GetContactData(String id)
{
String number = null;
Cursor phones = getApplicationContext().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id, null, null);
if(phones.moveToFirst())
{
number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();
return number;
}
此函数返回错误的数字,我也试图获取联系人姓名,但它也返回错误的名称,如何从recipient_id获取正确的联系人姓名?