rawContact数据插入

raw contact的主表(本身数据)的插入
示例1如:

        String accountType=null;         String accountName=null;         Account acct=getAccount();         if(acct!=null)         {             accountType=acct.type;             accountName=acct.name;         }          ContentValues values = new ContentValues();          values.put(RawContacts.ACCOUNT_TYPE, accountType);          values.put(RawContacts.ACCOUNT_NAME, accountName);          Uri rawContactUri = getContentResolver().insert(RawContacts.CONTENT_URI, values);          values.clear();          /*          这里取得了rawContactId          */          long rawContactId = ContentUris.parseId(rawContactUri); RawContacts.ACCOUNT_TYPE,RawContacts.ACCOUNT_NAME可以通过如下方法得到:     Account getAccount()     {          AccountManager am = AccountManager.get(this);         Account[] accounts = am.getAccounts();         HashSet<String> contactAccountTypes =new HashSet<String>();         SyncAdapterType[] syncs         = ContentResolver.getSyncAdapterTypes();          for (SyncAdapterType sync : syncs) {               if (ContactsContract.AUTHORITY.equals(sync.authority) &&          sync.supportsUploading()) {                    contactAccountTypes.add(sync.accountType);               }                   }          ArrayList<Account> contactAccounts=new ArrayList<Account>();           for (Account acct: accounts) {                  if (contactAccountTypes.contains(acct.type)) {                     contactAccounts.add(acct);                  }                             }           if(contactAccounts.size()==0)               return null;           int index=random.nextInt();           if(index<0)               index=-index;           index=index%contactAccounts.size();           return contactAccounts.get(index);     }

注意:需要android.permission.GET_ACCOUNTS权限
示例2:
 Raw contacts can be inserted incrementally or in a batch. The incremental method is more traditional but less efficient. It should be used only if no ContactsContract.RawContacts.Data  values are available at the time the raw contact is created:

 ContentValues values = new ContentValues();  values.put(RawContacts.ACCOUNT_TYPE, accountType);  values.put(RawContacts.ACCOUNT_NAME, accountName);  Uri rawContactUri = getContentResolver().insert(RawContacts.CONTENT_URI, values);  long rawContactId = ContentUris.parseId(rawContactUri);

 
Once ContactsContract.RawContacts.Data values become available, insert those. For example, here's how you would insert a name:
 values.clear();

 values.put(Data.RAW_CONTACT_ID, rawContactId);  values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);  values.put(StructuredName.DISPLAY_NAME, "Mike Sullivan");  getContentResolver().insert(Data.CONTENT_URI, values);

The batch method is by far preferred. It inserts the raw contact and its constituent data rows in a single database transaction and causes at most one aggregation pass.

 ArrayList<ContentProviderOperation> ops = Lists.newArrayList();//@2
 ...
 int rawContactInsertIndex = ops.size();//@3

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

 //下面插入子表信息

 ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)           .withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)//@4           .withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)           .withValue(StructuredName.DISPLAY_NAME, "Mike Sullivan")           .build());  getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);  

Note the use of withValueBackReference(String, int) t refer to the as-yet-unknown index value of the raw contact inserted in the first operation
注意1:该示例来自于文档:http://developer.android.com/reference/android/provider/ContactsContract.RawContacts.html
注意2:ArrayList<ContentProviderOperation> ops = Lists.newArrayList();
这里Lists.newArrayList()没找到。没看到Lists类。不过写成如下就可以了。
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
注意3: int rawContactInsertIndex = ops.size();这里算得该数据库操作在ops中的索引号。
注意4:withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)中的rawContactInsertIndex指明了
在ops的第rawContactInsertIndex个数据库操作结果中取得Data.RAW_CONTACT_ID所需要的数据。

注意5:对于StructuredName,只能插入一条,因为第二条会覆盖你第一条。
实例1:

import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.HashSet; import android.app.Activity; import android.app.ListActivity; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.content.Context; import android.content.ContentValues; import android.database.Cursor; import android.view.LayoutInflater; import android.view.View; import android.widget.ListView; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.CursorAdapter; import android.widget.ResourceCursorAdapter; import android.widget.TextView; import android.provider.ContactsContract; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.RawContacts; import android.provider.ContactsContract.Data; import android.view.View.OnClickListener;      import android.widget.Button;  import android.util.Log; import android.widget.HeaderViewListAdapter; import android.widget.ListAdapter; import android.content.ContentUris; import android.provider.ContactsContract.CommonDataKinds.StructuredName; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.CommonDataKinds.Organization; import android.accounts.Account; import android.accounts.AccountManager; import android.content.SyncAdapterType; import android.content.ContentResolver; import android.content.ContentProviderOperation; public class HelloCursor extends ListActivity {     private static String[] PROJECTION = new String[] {         Contacts._ID, // 0         Contacts.DISPLAY_NAME, // 1         Contacts.STARRED, // 2         Contacts.TIMES_CONTACTED, // 3         Contacts.CONTACT_PRESENCE, // 4         Contacts.PHOTO_ID, // 5         Contacts.LOOKUP_KEY, // 6         Contacts.HAS_PHONE_NUMBER, // 7          };     final static String querySelect = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("     + Contacts.HAS_PHONE_NUMBER + "=1) AND ("     + Contacts.DISPLAY_NAME + " != '' ))";     /** Called when the activity is first created. */     @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.main);         Cursor c = getContentResolver().query(Contacts.CONTENT_URI, null,                 null, null, Contacts.DISPLAY_NAME + " COLLATE NOCASE");         startManagingCursor(c);         MyResourceCursorAdapter adapter = new MyResourceCursorAdapter(this, R.layout.list_row,                 c);         this.setListAdapter(adapter);         Button button = (Button)findViewById(R.id.Button01);          OnClickListener listener=new OnClickListener(){             @Override                 public void onClick(View v) {                      cmd=CMD_ADD;                      doAction();                  }                  };         button.setOnClickListener(listener);         Button button2 = (Button)findViewById(R.id.Button02);          OnClickListener listener2=new OnClickListener(){             @Override                 public void onClick(View v) {                      cmd=CMD_ADD2;                 doAction();                  }                  };         button2.setOnClickListener(listener2);         Button button3 = (Button)findViewById(R.id.Button03);          OnClickListener listener3=new OnClickListener(){             @Override                 public void onClick(View v) {                      cmd=CMD_DELETE_ALL;                 doAction();                  }                  };         button3.setOnClickListener(listener3);         mHandler = new Handler();             }     private String[] kNames = { "hubin", "hudashi", "robin" };     int cnt = 0;      private Handler mHandler;     int cmd=0;     final int CMD_ADD=1;     final int CMD_ADD2=2;     final int CMD_DELETE_ALL=3;     class ContactThread implements Runnable {         public void run() {             //HelloCursor.this.getListView().invalidateViews();             if(cmd==CMD_ADD)             {             addContacts();             }             else if (cmd==CMD_ADD2)             {                 addContactByBatch();             }             else if (cmd==CMD_DELETE_ALL)             {                 dealAllContacts();             }                          cnt++;         }     }     Random random=new Random(System.currentTimeMillis());     void addContacts()     {         int randomNumber = 0;         //ContentValues newValues = new ContentValues();         randomNumber = (int) (Math.random() % 10);         /*for (int i = 0; i < kNames.length; i++) {             tempString = mStrings + cnt + randomNumber;             newValues.put(Contacts.DISPLAY_NAME, tempString);             getContentResolver().insert(RawContacts.CONTENT_URI, newValues);             newValues.clear();         }*/         String accountType=null;         String accountName=null;         Account acct=getAccount();         if(acct!=null)         {             accountType=acct.type;             accountName=acct.name;         }          ContentValues values = new ContentValues();          values.put(RawContacts.ACCOUNT_TYPE, accountType);          values.put(RawContacts.ACCOUNT_NAME, accountName);          Uri rawContactUri = getContentResolver().insert(RawContacts.CONTENT_URI, values);          values.clear();          long rawContactId = ContentUris.parseId(rawContactUri);          randomNumber = (int) (random.nextInt() % 10);          if(randomNumber<0)              randomNumber=-randomNumber;          String name=kNames[randomNumber%kNames.length] + cnt + randomNumber;          //下面插入子表信息          values.put(Data.RAW_CONTACT_ID, rawContactId);          values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);          values.put(StructuredName.DISPLAY_NAME, name);          values.put(StructuredName.GIVEN_NAME, "Given name");          values.put(StructuredName.FAMILY_NAME, "Family name");          values.put(StructuredName.PREFIX, "Sir");          values.put(StructuredName.SUFFIX, "Sr");          values.put(StructuredName.FAMILY_NAME, "Family name");          values.put(StructuredName.PHONETIC_FAMILY_NAME, "PF");          values.put(StructuredName.PHONETIC_GIVEN_NAME, "PG");          values.put(StructuredName.PHONETIC_MIDDLE_NAME, "PM");          getContentResolver().insert(Data.CONTENT_URI, values);                    values.clear();          values.put(Data.RAW_CONTACT_ID, rawContactId);          values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);          values.put(Phone.NUMBER, "1-800-GOOG-41");          values.put(Phone.TYPE, Phone.TYPE_CUSTOM);          values.put(Phone.LABEL, "free directory assistance");          Uri dataUri = getContentResolver().insert(Data.CONTENT_URI, values);                    values.clear();          values.put(Data.RAW_CONTACT_ID, rawContactId);          values.put(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE);          values.put(Email.DATA, "hudashi@sohu.com");          values.put(Email.TYPE, Email.TYPE_HOME);          values.put(Email.LABEL, "home email");          dataUri = getContentResolver().insert(Data.CONTENT_URI, values);                    values.clear();          values.clear();          values.put(Data.RAW_CONTACT_ID, rawContactId);          values.put(Data.MIMETYPE, Organization.CONTENT_ITEM_TYPE);          values.put(Organization.COMPANY, "gameloft");          values.put(Organization.TYPE, Organization.TYPE_WORK);          values.put(Organization.LABEL, "lable");          values.put(Organization.DEPARTMENT, "consult");          values.put(Organization.JOB_DESCRIPTION, "programe");          values.put(Organization.OFFICE_LOCATION, "room1");          values.put(Organization.SYMBOL, "123");          values.put(Organization.TITLE, "SSE");          dataUri = getContentResolver().insert(Data.CONTENT_URI, values);         Log.i("hubin","add");     }     void addContactByBatch()     {         int randomNumber = 0;         randomNumber = (int) (Math.random() % 10);         String accountType=null;         String accountName=null;         ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();         Account acct=getAccount();         if(acct!=null)         {             accountType=acct.type;             accountName=acct.name;         }         for(int i=0;i<3;i++)         {             int rawContactInsertIndex=ops.size();          ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)                   .withValue(RawContacts.ACCOUNT_TYPE, accountType)                   .withValue(RawContacts.ACCOUNT_NAME, accountName)                   .build());          randomNumber = (int) (random.nextInt() % 10);          if(randomNumber<0)              randomNumber=-randomNumber;          String name=kNames[randomNumber%kNames.length] + (cnt++);          //下面插入子表信息          ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)                  .withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)                  .withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)                  .withValue(StructuredName.DISPLAY_NAME, name)                  .withValue(StructuredName.GIVEN_NAME,  "Given name")                  .withValue(StructuredName.FAMILY_NAME, "Family name")                  .withValue(StructuredName.PREFIX, "Sir")                  .withValue(StructuredName.SUFFIX, "Sr")                  .withValue(StructuredName.FAMILY_NAME, "Family name")                  .withValue(StructuredName.PHONETIC_FAMILY_NAME,"PF")                  .withValue(StructuredName.PHONETIC_GIVEN_NAME, "PG")                  .withValue(StructuredName.PHONETIC_MIDDLE_NAME,"PM")                  .build()                            );          ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)                  .withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)                  .withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)                  .withValue(Phone.NUMBER, "1-800-GOOG-41")                  .withValue(Phone.TYPE, Phone.TYPE_CUSTOM)                  .withValue(Phone.LABEL,"free directory assistance")                  .build()                  );          ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)                  .withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)                  .withValue(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE)                  .withValue(Phone.NUMBER, "1-800-GOOG-42")                  .withValue(Phone.TYPE, Phone.TYPE_CUSTOM)                  .withValue(Phone.LABEL,"free directory assistance")                  .build()                  );          ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)                  .withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)                  .withValue(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE)                  .withValue(Email.DATA, "hudashi@sohu.com")                  .withValue(Email.TYPE, Email.TYPE_HOME)                  .withValue(Email.LABEL,"home email")                  .build()                  );                   ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)                  .withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)                  .withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)                  .withValue(Organization.COMPANY, "gameloft")                  .withValue(Organization.TYPE, Organization.TYPE_WORK)                  .withValue(Organization.LABEL, "lable")                  .withValue(Organization.DEPARTMENT, "consult")                  .withValue(Organization.JOB_DESCRIPTION, "programe")                  .withValue(Organization.OFFICE_LOCATION, "room1")                  .withValue(Organization.SYMBOL, "123")                  .withValue(Organization.TITLE, "SSE")                  .build()                  );         }          try{          getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);          }catch(Exception e)          {              e.printStackTrace();          }         Log.i("hubin","addByBatch");     }     Account getAccount()     {          AccountManager am = AccountManager.get(this);         Account[] accounts = am.getAccounts();         HashSet<String> contactAccountTypes =new HashSet<String>();         SyncAdapterType[] syncs         = ContentResolver.getSyncAdapterTypes();          for (SyncAdapterType sync : syncs) {               if (ContactsContract.AUTHORITY.equals(sync.authority) &&          sync.supportsUploading()) {                    contactAccountTypes.add(sync.accountType);               }                   }          ArrayList<Account> contactAccounts=new ArrayList<Account>();           for (Account acct: accounts) {                  if (contactAccountTypes.contains(acct.type)) {                     contactAccounts.add(acct);                  }                             }           if(contactAccounts.size()==0)               return null;           int index=random.nextInt();           if(index<0)               index=-index;           index=index%contactAccounts.size();           return contactAccounts.get(index);     }     void dealAllContacts()     {         getContentResolver().delete(RawContacts.CONTENT_URI, null, null);         Log.i("hubin","delete");     }     ContactThread contactDealer=new ContactThread();     void doAction()     {          mHandler.post(contactDealer);     } } class MyResourceCursorAdapter extends ResourceCursorAdapter {     public MyResourceCursorAdapter(Context context, int resource, Cursor cursor) {         super(context,resource,cursor);     }     public View newView(Context context, Cursor cursor, ViewGroup parent) {         return super.newView(context, cursor, parent);     }     @Override     public void bindView(View view, Context context, Cursor cursor) {         TextView nameView = (TextView) view;         // Set the name         nameView.setText(cursor                 .getString(cursor.getColumnIndex("DISPLAY_NAME")));     } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值