fragment_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.johnny.testcontacts.MainActivity$PlaceholderFragment" > <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="查询所有联系人" android:onClick="queryContact"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="插入单个联系人" android:onClick="insertContact"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="插入多个联系人" android:onClick="insertContacts"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="删除CBA" android:onClick="deleteContactsCBA"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="删除NBA" android:onClick="deleteContactsNBA"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="删除NBA易建联" android:onClick="deleteContactsNBAYI"/> </LinearLayout> </RelativeLayout>
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.johnny.testcontacts" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="14" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.johnny.testcontacts.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <provider android:name="com.johnny.testcontacts.ContactsContentProvider" android:authorities="com.example.johnny.contentprovider" android:exported="false" android:enabled="true" > </provider> </application> </manifest>
package com.johnny.testcontacts; public class ContactsBean { private String name; private String telephone; private long createDate; private String content; private String groupName; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public long getCreateDate() { return createDate; } public void setCreateDate(long createDate) { this.createDate = createDate; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getGroupName() { return groupName; } public void setGroupName(String groupName) { this.groupName = groupName; } }
package com.johnny.testcontacts; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.util.Log; public class ContactsContentProvider extends ContentProvider { //必须和AndroidManifest.xml中的android:authorities保持一致 public static final String AUTHORITY = "com.example.johnny.contentprovider"; public static final Uri AUTHORITY_URI = Uri.parse("content://" + AUTHORITY); public static final String PARAM_GROUP_BY = "groupBy"; public static final String PARAM_LIMIT = "limit"; private SQLiteOpenHelper mOpenHelper; public static interface ContactsUri{ static final String CONTACTS = "contacts"; public static final Uri URI_CONTACTS = Uri.withAppendedPath( AUTHORITY_URI, CONTACTS); } static interface ContactsMatch { public static final int CONTACTS = 0x0001; } static final UriMatcher URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH); static { final UriMatcher matcher = URI_MATCHER; matcher.addURI(AUTHORITY, ContactsUri.CONTACTS, ContactsMatch.CONTACTS); } @Override public boolean onCreate() { mOpenHelper = DBOpenHelper.newInstance(getContext()); return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteDatabase db = mOpenHelper.getReadableDatabase(); final int match = URI_MATCHER.match(uri); SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); String limit = uri.getQueryParameter(PARAM_LIMIT); String groupBy = uri.getQueryParameter(PARAM_GROUP_BY); switch (match) { case ContactsMatch.CONTACTS: qb.setTables(DBOpenHelper.ContactsTAB.TABLE_NAME); break; default: throw new UnsupportedOperationException("Unknown URL " + uri.toString()); } Cursor cursor = qb.query(db, projection, selection, selectionArgs, groupBy, null, sortOrder, limit); return cursor; } @Override public String getType(Uri uri) { return null; } @Override public Uri insert(Uri uri, ContentValues contentValues) { int match = URI_MATCHER.match(uri); final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); long id = -1; switch (match) { case ContactsMatch.CONTACTS: id = db.insert(DBOpenHelper.ContactsTAB.TABLE_NAME, null, contentValues); break; default: throw new UnsupportedOperationException("Unknown insert URI " + uri); } if (id >= 0) { getContext().getContentResolver().notifyChange(uri,null); return ContentUris.withAppendedId(uri, id); } else { return null; } } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { final int match = URI_MATCHER.match(uri); final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); int deleted = 0; switch (match) { case ContactsMatch.CONTACTS: deleted = db.delete(DBOpenHelper.ContactsTAB.TABLE_NAME, selection, selectionArgs); break; default: throw new UnsupportedOperationException("Unknown delete URI " + uri); } if (deleted > 0) { getContext().getContentResolver().notifyChange(uri,null); } return deleted; } @Override public int update(Uri uri, ContentValues contentValues, String selection, String[] selectionArgs) { int match = URI_MATCHER.match(uri); final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); int modified = 0; switch (match) { case ContactsMatch.CONTACTS: modified = db.update(DBOpenHelper.ContactsTAB.TABLE_NAME, contentValues, selection, selectionArgs); break; default: throw new UnsupportedOperationException("Unknown update URI " + uri); } if (modified > 0) { getContext().getContentResolver().notifyChange(uri,null); } return modified; } }
package com.johnny.testcontacts; import android.content.ContentProviderOperation; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.net.Uri; import android.util.Log; import java.util.ArrayList; /** * Created by heqiang on 15-1-16. */ public class DBOpenHelper extends SQLiteOpenHelper{ private final static String TAG = "ContactsTAB"; private static final String DB_NAME = "testcontacts.db"; private static final int DB_VERSION = 1; public final Object CONTACTS_TABLE_LOCK = new Object(); private static Context mContext; private static DBOpenHelper sInstance; private DBOpenHelper(Context context){ super(context, DB_NAME, null, DB_VERSION); } public static synchronized DBOpenHelper newInstance(Context context) { if (sInstance == null) { sInstance = new DBOpenHelper(context); mContext = context; } return sInstance; } public static synchronized DBOpenHelper getInstance() { return sInstance; } public static final class ContactsTAB{ public static final String TABLE_NAME = "contacts"; public static final String _ID = "_id"; public static final String CONTACT_NAME = "name"; public static final String CONTACT_TELEPHONE = "telephone"; public static final String CONTACT_CREATE_DATE = "create_date"; public static final String CONTACT_CONTENT = "content"; public static final String CONTACT_GROUP = "group_name"; public static ContentValues parseContentValuse(ContactsBean bean){ ContentValues contentValues = new ContentValues(); contentValues.put(ContactsTAB.CONTACT_NAME,bean.getName()); contentValues.put(ContactsTAB.CONTACT_TELEPHONE,bean.getTelephone()); contentValues.put(ContactsTAB.CONTACT_CREATE_DATE,bean.getCreateDate()); contentValues.put(ContactsTAB.CONTACT_CONTENT,bean.getContent()); contentValues.put(ContactsTAB.CONTACT_GROUP,bean.getGroupName()); return contentValues; } } static interface SQLS { public static final String SQL_CREATE_CONTACTS_TABLE = "CREATE TABLE " + ContactsTAB.TABLE_NAME + " (" + ContactsTAB._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + ContactsTAB.CONTACT_NAME + " TEXT," + ContactsTAB.CONTACT_TELEPHONE + " TEXT," + ContactsTAB.CONTACT_GROUP +" TEXT," + ContactsTAB.CONTACT_CONTENT +" TEXT," + ContactsTAB.CONTACT_CREATE_DATE + " INTEGER" + ");" ; } @Override public void onCreate(SQLiteDatabase db) { createTables(db); } @Override public void onUpgrade(SQLiteDatabase db, int i, int i2) { } private void createTables(SQLiteDatabase db) { db.execSQL(SQLS.SQL_CREATE_CONTACTS_TABLE); } private void doApplyOperations(Uri uri, ArrayList<ContentProviderOperation> ops) { try { mContext.getContentResolver().applyBatch(uri.getAuthority(), ops); } catch (Exception e) { Log.d(TAG, "doApplyOperations error!", e); } } public void insertContact(ContactsBean bean){ ContentValues contentValues = ContactsTAB.parseContentValuse(bean); mContext.getContentResolver().insert(ContactsContentProvider.ContactsUri.URI_CONTACTS, contentValues); } public void insertContacts(ArrayList<ContactsBean> beans){ Uri uri = ContactsContentProvider.ContactsUri.URI_CONTACTS; ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); for(ContactsBean bean : beans){ ContentValues contentValues = ContactsTAB.parseContentValuse(bean); ContentProviderOperation operation = ContentProviderOperation .newInsert(uri).withValues(contentValues).build(); ops.add(operation); } synchronized (CONTACTS_TABLE_LOCK) { doApplyOperations(uri, ops); } } public void deleteContactsByContent(String group){ mContext.getContentResolver().delete(ContactsContentProvider.ContactsUri.URI_CONTACTS, ContactsTAB.CONTACT_CONTENT + "=?", new String []{ group } ); } public void deleteContactsByContentAndName(String group,String name){ mContext.getContentResolver().delete(ContactsContentProvider.ContactsUri.URI_CONTACTS, ContactsTAB.CONTACT_CONTENT + "=? AND " + ContactsTAB.CONTACT_NAME + "=?", new String []{ group, name} ); } public ArrayList<ContactsBean> queryAllContacts(){ ArrayList<ContactsBean> beans = new ArrayList<ContactsBean>(); Cursor c = null; c = mContext.getContentResolver().query(ContactsContentProvider.ContactsUri.URI_CONTACTS, null, null, null, null); if (c != null && c.moveToFirst()) { do { ContactsBean bean = new ContactsBean(); bean.setName(c.getString(c.getColumnIndex(ContactsTAB.CONTACT_NAME))); bean.setContent(c.getString(c.getColumnIndex(ContactsTAB.CONTACT_CONTENT))); bean.setCreateDate(c.getLong(c.getColumnIndex(ContactsTAB.CONTACT_CREATE_DATE))); bean.setGroupName(c.getString(c.getColumnIndex(ContactsTAB.CONTACT_GROUP))); bean.setTelephone(c.getString(c.getColumnIndex(ContactsTAB.CONTACT_TELEPHONE))); beans.add(bean); }while(c.moveToNext()); c.close(); } return beans; } }
package com.johnny.testcontacts; import java.util.ArrayList; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.database.ContentObserver; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.os.Build; public class MainActivity extends ActionBarActivity { private DBOpenHelper mDBOpenHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, new PlaceholderFragment()).commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); mDBOpenHelper = DBOpenHelper.getInstance(); getContentResolver().registerContentObserver(ContactsContentProvider.ContactsUri.URI_CONTACTS, true, mContentObserver); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); return rootView; } } public void queryContact(View view){ new Thread(new Runnable() { @Override public void run() { ArrayList<ContactsBean> beans = mDBOpenHelper.queryAllContacts(); for(ContactsBean bean : beans){ Log.e("Test","----------------------"); Log.e("Test","name = "+bean.getName()); Log.e("Test","content = "+bean.getContent()); Log.e("Test","groupName = "+bean.getGroupName()); Log.e("Test","telephone = "+bean.getTelephone()); Log.e("Test","createDate = "+bean.getCreateDate()); Log.e("Test","----------------------"); } } }).start(); } public void insertContact(View view){ new Thread(new Runnable() { @Override public void run() { ContactsBean bean = new ContactsBean(); bean.setName("James"); bean.setGroupName("East"); bean.setTelephone("13700000000"); bean.setCreateDate(System.currentTimeMillis()); bean.setContent("NBA"); mDBOpenHelper.insertContact(bean); } }).start(); } public void insertContacts(View view){ new Thread(new Runnable() { @Override public void run() { ArrayList<ContactsBean> beans = new ArrayList<ContactsBean>(); ContactsBean bean = new ContactsBean(); bean.setName("Park"); bean.setGroupName("West"); bean.setTelephone("13711111111"); bean.setCreateDate(System.currentTimeMillis()); bean.setContent("NBA"); beans.add(bean); bean = new ContactsBean(); bean.setName("YiJianLian"); bean.setGroupName("South"); bean.setTelephone("135000000"); bean.setCreateDate(System.currentTimeMillis()); bean.setContent("CBA"); beans.add(bean); bean = new ContactsBean(); bean.setName("YiJianLian"); bean.setGroupName("East"); bean.setTelephone("13599999999"); bean.setCreateDate(System.currentTimeMillis()); bean.setContent("NBA"); beans.add(bean); mDBOpenHelper.insertContacts(beans); } }).start(); } public void deleteContactsCBA(View view){ new Thread(new Runnable() { @Override public void run() { mDBOpenHelper.deleteContactsByContent("CBA"); } }).start(); } public void deleteContactsNBA(View view){ new Thread(new Runnable() { @Override public void run() { mDBOpenHelper.deleteContactsByContent("NBA"); } }).start(); } public void deleteContactsNBAYI(View view){ new Thread(new Runnable() { @Override public void run() { mDBOpenHelper.deleteContactsByContentAndName("NBA", "YiJianLian"); } }).start(); } private ContentObserver mContentObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { super.onChange(selfChange); new Thread(new Runnable() { @Override public void run() { ArrayList<ContactsBean> beans = mDBOpenHelper.queryAllContacts(); for(ContactsBean bean : beans){ Log.e("Test","----------------------"); Log.e("Test","name = "+bean.getName()); Log.e("Test","content = "+bean.getContent()); Log.e("Test","groupName = "+bean.getGroupName()); Log.e("Test","telephone = "+bean.getTelephone()); Log.e("Test","createDate = "+bean.getCreateDate()); Log.e("Test","----------------------"); } } }).start(); } }; }