我想添加新的联系人,当我调试我没有发现任何错误但仍然无法添加新的联系人。请查看我的代码并指导我。
我的代码:
public final class contactadder extends Activity
{
private EditText ETCname;
private EditText ETCPhNo;
private EditText ETCEmailId;
private Button btnSave;
String ss;
public static final String TAG = "ContactsAdder";
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.contact_adder);
ETCname=(EditText)findViewById(R.id.contactNameEditText);
ETCPhNo=(EditText)findViewById(R.id.contactPhoneEditText);
ETCEmailId=(EditText)findViewById(R.id.contactEmailEditText);
btnSave=(Button)findViewById(R.id.contactSaveButton);
btnSave.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String name=ETCname.getText().toString();
String phone=ETCPhNo.getText().toString();
String email=ETCEmailId.getText().toString();
ArrayList<ContentProviderOperation> op=new ArrayList<ContentProviderOperation>();
/* ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, mSelectedAccount.getType())
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, mSelectedAccount.getName())
.build()); */
op.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name)
.build());
op.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER,phone).build());
Log.i(TAG,"Creating contact: " + name);
try
{
getContentResolver().applyBatch(ContactsContract.AUTHORITY, op);
launchContactManager();
}catch (Exception e)
{
Context ctx = getApplicationContext();
CharSequence txt = "Contact creation failed, check logs.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(ctx, txt, duration);
toast.show();
//log exception
Log.e(TAG, "Exceptoin encoutered while inserting contact: " + e);
}
}
}
答案 0 :(得分:0)
粗略地看一下您的代码会在onClick
函数的第5行显示错误:
ArrayList<ContentProviderOperation> op=new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
您声明ArrayList
“op”,然后您的下一行引用“ops”
修好后,注意到你的评论没有错误。logcat
是否列出了任何错误?
您的manifest.xml是否正确声明了权限?您需要声明<uses-permission android:name="android.permission.WRITE_CONTACTS" />
。