我正在尝试创建一个类,其字段是联系信息(姓名、地址等)。
public class ContactObject {
private Activity actividad;
private Uri contactUri;`enter code here`
// variable para asegurarse que la consulta de contacto se realizó correctamente
private boolean isOK = true;
private String displayName;
private String givenName;
private String familyName;
private String region;
private String postcode;
private String city;
private String street;
public ContactObject(Activity actividad, Uri contactUri) {
super();
this.actividad = actividad;
this.contactUri = contactUri;
Cursor c = null;
try{
String[] selection = new String[]{
ContactsContract.CommonDataKinds.StructuredPostal.STREET,
ContactsContract.CommonDataKinds.StructuredPostal.CITY,
ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE,
ContactsContract.CommonDataKinds.StructuredPostal.REGION,
ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME,
ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME,
ContactsContract.Contacts.DISPLAY_NAME
};
c = actividad.getContentResolver().query(contactUri, selection,null, null, null);
if (c != null && c.moveToFirst()) {
this.street = c.getString(0);
this.city = c.getString(1);
this.postcode = c.getString(2);
this.region = c.getString(3);
this.givenName = c.getString(4);
this.familyName = c.getString(5);
this.displayName = c.getString(6);
}
}catch(Exception e){
CLog.e("peta constructor ContactObject: " + e.getMessage());
isOK = false;
}
}
// getters and setters
}
// code to launch contact picker
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
Contacts.CONTENT_URI);
startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);
// code to create the ContactObject
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
Uri uri = data.getData();
if (uri != null) {
ContactObject co = new ContactObject(actividad, uri);
String mensaje;
if (co.isOK()){
mensaje = "Contacto encontrado: " + co.getDisplayName();
}else{
mensaje = "error recuperando datos del contacto " + uri.toString();
}
CToast.mensajeLargo(mensaje, actividad.getApplicationContext());
}
}
}
}
在模拟器中,我创建了几个联系人(只有姓名和电话)。在测试应用程序中,我调用 contactPicker onResult,并使用联系人 uri 创建 ContactObject。当我执行它时,它会抛出一个异常,它的消息是“无效的列 data4”。
正如我所收集的,“data4”是常量 ContactsContract.CommonDataKinds.StructuredPostal.STREET 的值。但是,如果我只查询 DISPLAY_NAME,我就可以毫无问题地得到它。
我知道这些联系人没有地址,但是我的许多(实际)电话联系人都没有地址,并且应用程序不会因此而崩溃。
我究竟做错了什么?