开发者

Inserting contact to Samsung I9000 Galaxy S returns an exception

I have this code for inserting contacts tested on all HTC devices and it seems to be working fine until I tried it on a Samsung I9000 Galaxy S which gives me a java.lang.NullPointerException on this particular line of code

String strDisplayName = "First Name" + " " + "LastName";
values.put(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, strDisplayName);
Uri rawContactUri = context.getContentResolver().insert(RawContacts.CONTENT_URI, values); //java.lang.NullPointerException here

It seems like this URI doesn't exist or maybe samsung has a different way on inserting contacts. Has anyone experience 开发者_如何转开发this on samsung galaxy device? Please share your thoughts.

Thanks


You are inserting into RawContacts but this does not have a column DISPLAY_NAME column. This is part of the RawContacts.Data entity. Your insert should look like this:

ArrayList<ContentProviderOperation> ops =
          new ArrayList<ContentProviderOperation>();

 int rawContactInsertIndex = ops.size();
 ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
          .build());

 ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
          .withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)
          .withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
          .withValue(StructuredName.DISPLAY_NAME, strDisplayName)
          .build());

 getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);

This code won't run on all devices though as you should also specifiy and account to create the contact in. Where do you want to create the contact? A phone contact? A google contact? IIRC I think on Galaxy S to create a phone contact you should set the account type and name to blank (not null). That would change the first operation to:

 ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
          .withValue(RawContacts.ACCOUNT_TYPE, "")
          .withValue(RawContacts.ACCOUNT_NAME, "")
          .build());


When debugging, you are able to "watch" your variables or you could test null variables.

Also, there's code missing: Where's the act (= activity?) coming from, that's probably the one which is NULL.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜