Android: ¿cómo agregar un contacto a la SIM usando el SDK?
Estoy escribiendo una aplicación que escribe contactos en la tarjeta SIM de un teléfono Android. Estoy atascado en el punto donde se agrega el número de teléfono: se produce una excepción sin razón aparente.
Aquí hay un fragmento de código.
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);
}
La aplicación tiene permisos android.permission.READ_CONTACTS y android.permission.WRITE_CONTACTS.
El teléfono muestra un contacto con el nombre pero sin teléfono (por cierto, al agregar el teléfono a ese contacto usando la interfaz de usuario normal, se agrega un nuevo contacto, con nombre y teléfono, y el contacto antiguo con el nombre solo permanece).
¿Alguna idea de por qué falla la tercera inserción (la segunda en la tabla de Datos), mientras que las 2 anteriores (1 en RawContacts y 1 en Data) tienen éxito?