Tôi đang viết một ứng dụng ghi danh bạ trong thẻ SIM của điện thoại Android. Tôi bị kẹt ở điểm mà số điện thoại được thêm vào: ngoại lệ xảy ra mà không có lý do rõ ràng.Android: cách thêm liên hệ vào SIM bằng SDK?
Dưới đây là một đoạn mã.
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.provider.ContactsContract.RawContacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContactsEntity;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.RawContacts.Entity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.widget.TextView;
[...]
try{
// add a row to the RawContacts table
ContentValues values = new ContentValues();
values.put(RawContacts.ACCOUNT_TYPE, "com.anddroid.contacts.sim");
values.put(RawContacts.ACCOUNT_NAME, "SIM");
Uri rawContactUri = getContentResolver().insert(RawContacts.CONTENT_URI, values);
// get the ID of the newly-added line
long rawContactId = ContentUris.parseId(rawContactUri);
// add a "name" line to the Data table, linking it to the new RawContact
// with the CONTACT_ID column
values.clear();
values.put(Data.RAW_CONTACT_ID, rawContactId);
values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
values.put(StructuredName.DISPLAY_NAME, "Name");
cr.insert(Data.CONTENT_URI, values);
// this insert succeeds
// add a "phone" line to the Data table, linking it to the new RawContact
// with the CONTACT_ID column
values.clear();
values.put(Data.CONTACT_ID, rawContactId);
values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
values.put(Phone.NUMBER, "+12345678901");
values.put(Phone.TYPE, Phone.TYPE_MOBILE);
cr.insert(Data.CONTENT_URI, values);
// this insert fails with a NullPointerException
}
catch(Exception e){
String xx=e.toString();
System.out.println(xx);
}
Ứng dụng này có quyền android.permission.READ_CONTACTS và android.permission.WRITE_CONTACTS.
Điện thoại hiển thị số liên lạc có tên nhưng không có điện thoại (ngẫu nhiên, thêm điện thoại vào liên lạc đó bằng kết quả UI bình thường trong một số liên lạc mới đang được thêm vào, với tên và điện thoại, và liên lạc cũ chỉ có tên) .
Bất kỳ ý tưởng nào tại sao chèn thứ ba (thứ hai trong bảng dữ liệu) không thành công, trong khi 2 lần trước (1 trong RawContacts và 1 trong dữ liệu) thành công?
Nó thực sự sẽ hữu ích nếu bạn đăng theo dõi ngăn xếp ngoại lệ quá – ognian
Ý của bạn là đặt điểm ngắt trong câu lệnh bắt và dán ngăn xếp dấu vết khi breakpoint được nhấn (có nghĩa là, ngoại lệ đã bị bắt)? Bạn có thể thấy chức năng nào đã ném ngoại lệ từ đó? Tuy nhiên, thay thế Data.CONTACT_ID với Data.RAW_CONTACT_ID giải quyết. – user377486