2017-09-06 43 views
3

一个非常奇怪的象征。我打算通过此规则更新联系人姓名: - 如果联系人姓名以“位”+空格(“位”)开头,则 - >将联系人姓名更新为name.substring(4,name.length()) ,这意味着联系人名称将更新,而不用“位”。更新联系人的名称更新(ContentProviderOperation)

当我使用name.substring从数字降低他们4(我认为,直到联系人的名称空间),它的工作完美。当我从4个字符开始使用时,联系人的姓名会增加。例如,当我使用name = name.substring(4,name.length()),而名称等于“bit Lili”时,它的更新为: Lili Lili。

private void updateContact(String name) { 
    ContentResolver cr = getContentResolver(); 
    String where = ContactsContract.Data.DISPLAY_NAME + " = ?"; 
    String[] params = new String[] {name}; 
    Cursor phoneCur = managedQuery(ContactsContract.Data.CONTENT_URI,null,where,params,null); 
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); 
    if ((null == phoneCur)) {//createContact(name, phone); 
     Toast.makeText(this, "no contact with this name", Toast.LENGTH_SHORT).show(); 
     return;} else {ops.add(ContentProviderOperation.newUpdate(android.provider.ContactsContract.Data.CONTENT_URI) 
       .withSelection(where, params) 
       .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name.substring(4,name.length())) 
       .build()); 
    } 

    phoneCur.close(); 

    try {cr.applyBatch(ContactsContract.AUTHORITY, ops);} 
    catch (RemoteException e) {e.printStackTrace();} 
    catch (OperationApplicationException e) {e.printStackTrace();}} 

谢谢!

回答

0

没有一定的答案,但它想工作,你有问题,是因为你需要根据你的问题

.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME //This specific part has a problem with the new update function 
      ,name.substring(4,name.length())) 

所以我的修正建议是将其更改为姓氏和名字更改这些你想删除给定的名称,所以它是一个解决方案

public static boolean updateContactName(@NonNull Context context, @NonNull String name) { 
    if (name.length() < 4) return true; 
    String givenNameKey = ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME; 
    String familyNameKey = ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME; 
    String changedName = name.substring(4, name.length()); 
    ArrayList<ContentProviderOperation> ops = new ArrayList<>(); 

    String where = ContactsContract.Data.DISPLAY_NAME + " = ?"; 
    String[] params = new String[]{name}; 

    ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI) 
      .withSelection(where, params) 
      .withValue(givenNameKey, changedName) 
      .withValue(familyNameKey, "") 
      .build()); 
    try { 
     context.getContentResolver() 
       .applyBatch(ContactsContract.AUTHORITY, ops); 
    } catch (Exception e) { 
     e.printStackTrace(); 
     return false; 
    } 
    return true; 
}