我正在创建一个Android应用程序,它将接受用户的前四位数字,不仅会从1-100开始逐行显示数字,还会将它们单独保存在联系人中。对于例如用户类型9179和TextView
将显示从9179000000到9179000100。
问题是我的代码是将单个联系人中的号码保存为个人号码。这是代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
test=(TextView)findViewById(R.id.textView1);
getit=(EditText)findViewById(R.id.editText1);
b=(Button)findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
StringBuilder t = new StringBuilder();
String result=getit.getText().toString();
for (int l=series; l<=100; l++) {
t.append(result);
t.append(String.format("%06d", l)+"\n");
}
test.setText(t.toString());
String sphone=test.getText().toString();
/* String result=getit.getText().toString();
test.setText(result); */
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
int rawContactInsertIndex = ops.size();
ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
.withValue(RawContacts.ACCOUNT_TYPE, null)
.withValue(RawContacts.ACCOUNT_NAME, null).build());
ops.add(ContentProviderOperation
.newInsert(Data.CONTENT_URI)
.withValueBackReference(
ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
.withValue(Phone.NUMBER, sphone) // Number of the person
.withValue(Phone.TYPE, Phone.TYPE_MOBILE).build()); // Type of mobile number
try
{
ContentProviderResult[] res = getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
}
catch (RemoteException e)
{
// error
e.printStackTrace();
}
catch (OperationApplicationException e)
{
// error
e.printStackTrace();
}
}
});
}
}
答案 0 :(得分:0)
我没有检查您的ContentProviderOperation
代码,但如果它正确且有效,则其余代码应如下所示。
你在for循环后只创建了1 String sphone
。相反,for循环应该扩展到ContentProviderOperation
对象的创建。使用此applyBatch
功能,您可以一次添加多个联系人。
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
final String result = getit.getText().toString();
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
for (int l=series; l<=100; l++) {
String sphone = result + String.format("%06d", l);
int rawContactInsertIndex = ops.size();
ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
.withValue(RawContacts.ACCOUNT_TYPE, null)
.withValue(RawContacts.ACCOUNT_NAME, null).build());
ops.add(ContentProviderOperation
.newInsert(Data.CONTENT_URI)
.withValueBackReference(
ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
.withValue(Phone.NUMBER, sphone) // Number of the person
.withValue(Phone.TYPE, Phone.TYPE_MOBILE).build()); // Type of mobile number
}
try {
ContentProviderResult[] res = getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
} catch (OperationApplicationException e) {
}
}