分享

Android ContentProviders数据共享

 w_hf的图书馆 2011-08-21

Android ContentProviders数据共享

1.创建Content Providers
Java代码 复制代码 收藏代码
  1. package com.Aina.Android;   
  2.   
  3. import android.net.Uri;   
  4. import android.provider.BaseColumns;   
  5.   
  6. /**  
  7.  * com.Aina.Android Pro_ContentProviders  
  8.  *   
  9.  * @author Aina.huang E-mail: 674023920@qq.com  
  10.  * @version 创建时间:2010 Jul 1, 2010 11:26:31 AM 类说明  
  11.  */  
  12. public class NotePad {   
  13.   
  14.     // Content Providers的URI   
  15.     public static final String AUTHORITY = "com.google.android.provider.notepad";   
  16.   
  17.     private NotePad() {   
  18.   
  19.     }   
  20.   
  21.     /**  
  22.      * 定义基本字段  
  23.      *   
  24.      * @author Aina_hk  
  25.      *   
  26.      */  
  27.     public static final class Notes implements BaseColumns {   
  28.         private Notes() {   
  29.   
  30.         }   
  31.   
  32.         public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY   
  33.                 + "/notes");   
  34.         // 新的MIME类型-多个   
  35.         public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.google.note";   
  36.         // 新的MIME类型-单个   
  37.         public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.google.note";   
  38.         // 默认排序   
  39.         public static final String DEFAULT_SORT_ORDER = "modified ASC";   
  40.         // 字段   
  41.         public static final String TITLE = "title";   
  42.         public static final String NOTE = "note";   
  43.         public static final String CREATEDDATE = "created";   
  44.         public static final String MODIFIEDDATE = "modified";   
  45.     }   
  46. }  


Java代码 复制代码 收藏代码
  1. package com.Aina.Android;   
  2.   
  3. import java.util.HashMap;   
  4.   
  5. import com.Aina.Android.NotePad.Notes;   
  6. import android.content.ContentProvider;   
  7. import android.content.ContentUris;   
  8. import android.content.ContentValues;   
  9. import android.content.Context;   
  10. import android.content.UriMatcher;   
  11. import android.content.res.Resources;   
  12. import android.database.Cursor;   
  13. import android.database.sqlite.SQLiteDatabase;   
  14. import android.database.sqlite.SQLiteOpenHelper;   
  15. import android.database.sqlite.SQLiteQueryBuilder;   
  16. import android.database.sqlite.SQLiteDatabase.CursorFactory;   
  17. import android.net.Uri;   
  18. import android.text.TextUtils;   
  19.   
  20. /**  
  21.  * com.Aina.Android Pro_ContentProviders  
  22.  *   
  23.  * @author Aina.huang E-mail: 674023920@qq.com  
  24.  * @version 创建时间:2010 Jul 1, 2010 11:55:55 AM 类说明  
  25.  */  
  26. public class NotePadProvider extends ContentProvider {   
  27.   
  28.     public static final String DATABASE_NAME = "test.db";   
  29.     public static final String TABLE_NAME = "notes";   
  30.     public static final int VERSION = 1;   
  31.     public static final int NOTES = 1;   
  32.     public static final int NOTE_ID = 2;   
  33.     public static HashMap<String, String> hm = null;   
  34.     public static UriMatcher mUriMatcher = null;   
  35.     public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME   
  36.             + " (" + Notes._ID + " INTEGER PRIMARY KEY," + Notes.TITLE   
  37.             + " TEXT," + Notes.NOTE + " TEXT," + Notes.CREATEDDATE   
  38.             + " INTEGER," + Notes.MODIFIEDDATE + " INTEGER)";   
  39.     private SQLiteDataHelper msdh = null;   
  40.     static {   
  41.         mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);   
  42.         mUriMatcher.addURI(NotePad.AUTHORITY, "notes", NOTES);   
  43.         mUriMatcher.addURI(NotePad.AUTHORITY, "notes/#", NOTE_ID);   
  44.         hm = new HashMap<String, String>();   
  45.         hm.put(Notes._ID, Notes._ID);   
  46.         hm.put(Notes.TITLE, Notes.TITLE);   
  47.         hm.put(Notes.NOTE, Notes.NOTE);   
  48.         hm.put(Notes.CREATEDDATE, Notes.CREATEDDATE);   
  49.         hm.put(Notes.MODIFIEDDATE, Notes.MODIFIEDDATE);   
  50.     }   
  51.   
  52.     private static class SQLiteDataHelper extends SQLiteOpenHelper {   
  53.   
  54.         public SQLiteDataHelper(Context context, String name,   
  55.                 CursorFactory factory, int version) {   
  56.             super(context, name, factory, version);   
  57.         }   
  58.   
  59.         @Override  
  60.         public void onCreate(SQLiteDatabase db) {   
  61.             db.execSQL(CREATE_TABLE);   
  62.   
  63.         }   
  64.   
  65.         @Override  
  66.         public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {   
  67.             db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);   
  68.             this.onCreate(db);   
  69.         }   
  70.   
  71.     }   
  72.   
  73.     /**  
  74.      * 删除  
  75.      */  
  76.     @Override  
  77.     public int delete(Uri uri, String selection, String[] selectionArgs) {   
  78.         SQLiteDatabase db = msdh.getWritableDatabase();   
  79.         int num = 0;   
  80.         switch (mUriMatcher.match(uri)) {   
  81.         case NOTES:   
  82.             num = db.delete(TABLE_NAME, selection, selectionArgs);   
  83.             break;   
  84.         case NOTE_ID:   
  85.             num = db.delete(TABLE_NAME, Notes._ID   
  86.                     + " = "  
  87.                     + uri.getPathSegments().get(1)   
  88.                     + (!TextUtils.isEmpty(selection) ? " AND (" + selection   
  89.                             + ')' : ""), selectionArgs);   
  90.             break;   
  91.         default:   
  92.             break;   
  93.         }   
  94.         this.getContext().getContentResolver().notifyChange(uri, null);   
  95.         return num;   
  96.     }   
  97.   
  98.     @Override  
  99.     public String getType(Uri uri) {   
  100.         String str = "";   
  101.         switch (mUriMatcher.match(uri)) {   
  102.         case NOTES:   
  103.             str = Notes.CONTENT_TYPE;   
  104.             break;   
  105.         case NOTE_ID:   
  106.             str = Notes.CONTENT_ITEM_TYPE;   
  107.             break;   
  108.         default:   
  109.             throw new IllegalArgumentException("Unknown URI " + uri);   
  110.         }   
  111.         return str;   
  112.     }   
  113.   
  114.     /**  
  115.      * 插入  
  116.      */  
  117.     @Override  
  118.     public Uri insert(Uri uri, ContentValues values) {   
  119.         if (mUriMatcher.match(uri) != NOTES) {   
  120.             throw new IllegalArgumentException("Unknown URI " + uri);   
  121.         }   
  122.         ContentValues cv = null;   
  123.         if (values == null) {   
  124.             cv = new ContentValues();   
  125.         } else {   
  126.             cv = new ContentValues(values);   
  127.         }   
  128.         long num = System.currentTimeMillis();   
  129.         if (cv.containsKey(Notes.CREATEDDATE) == false) {   
  130.             cv.put(Notes.CREATEDDATE, num);   
  131.         }   
  132.         if (cv.containsKey(Notes.MODIFIEDDATE) == false) {   
  133.             cv.put(Notes.MODIFIEDDATE, num);   
  134.         }   
  135.         if (cv.containsKey(Notes.TITLE) == false) {   
  136.             Resources r = Resources.getSystem();   
  137.             cv.put(Notes.TITLE, r.getString(android.R.string.untitled));   
  138.         }   
  139.         if (cv.containsKey(Notes.NOTE) == false) {   
  140.             cv.put(Notes.NOTE, "");   
  141.         }   
  142.         SQLiteDatabase db = msdh.getWritableDatabase();   
  143.         long id = db.insertOrThrow(TABLE_NAME, Notes.NOTE, cv);   
  144.         if (id > 0) {   
  145.             Uri uri_new = ContentUris.withAppendedId(uri, id);   
  146.             this.getContext().getContentResolver().notifyChange(uri_new, null);   
  147.             return uri_new;   
  148.         }   
  149.         return null;   
  150.     }   
  151.   
  152.     @Override  
  153.     public boolean onCreate() {   
  154.         msdh = new SQLiteDataHelper(this.getContext(), TABLE_NAME, null,   
  155.                 VERSION);   
  156.         return true;   
  157.     }   
  158.   
  159.     /**  
  160.      * 查询  
  161.      */  
  162.     @Override  
  163.     public Cursor query(Uri uri, String[] projection, String selection,   
  164.             String[] selectionArgs, String sortOrder) {   
  165.         SQLiteQueryBuilder qb = new SQLiteQueryBuilder();   
  166.         switch (mUriMatcher.match(uri)) {   
  167.         case NOTES:   
  168.             qb.setTables(TABLE_NAME);   
  169.             qb.setProjectionMap(hm);   
  170.             break;   
  171.         case NOTE_ID:   
  172.             qb.setTables(TABLE_NAME);   
  173.             qb.setProjectionMap(hm);   
  174.             qb.appendWhere(Notes._ID + " = " + uri.getPathSegments().get(1));   
  175.             break;   
  176.         default:   
  177.             throw new IllegalArgumentException("Unknown URI " + uri);   
  178.         }   
  179.         String orderBy = "";   
  180.         if (TextUtils.isEmpty(sortOrder)) {   
  181.             orderBy = Notes.DEFAULT_SORT_ORDER;   
  182.         } else {   
  183.             orderBy = sortOrder;   
  184.         }   
  185.         SQLiteDatabase db = msdh.getReadableDatabase();   
  186.         Cursor cursor = qb.query(db, projection, selection, selectionArgs,   
  187.                 nullnull, orderBy);   
  188.         cursor.setNotificationUri(this.getContext().getContentResolver(), uri);   
  189.         return cursor;   
  190.     }   
  191.   
  192.     /**  
  193.      * 更新  
  194.      */  
  195.     @Override  
  196.     public int update(Uri uri, ContentValues values, String selection,   
  197.             String[] selectionArgs) {   
  198.         SQLiteDatabase db = msdh.getWritableDatabase();   
  199.         int num = 0;   
  200.         switch (mUriMatcher.match(uri)) {   
  201.         case NOTES:   
  202.             num = db.update(TABLE_NAME, values, selection, selectionArgs);   
  203.             break;   
  204.         case NOTE_ID:   
  205.             num = db.update(TABLE_NAME, values, Notes._ID   
  206.                     + " = "  
  207.                     + uri.getPathSegments().get(1)   
  208.                     + (!TextUtils.isEmpty(selection) ? " and (" + selection   
  209.                             + ")" : ""), selectionArgs);   
  210.         default:   
  211.             break;   
  212.         }   
  213.         this.getContext().getContentResolver().notifyChange(uri, null);   
  214.         return num;   
  215.     }   
  216. }  


Java代码 复制代码 收藏代码
  1. package com.Aina.Android;   
  2.   
  3. import com.Aina.Android.NotePad.Notes;   
  4.   
  5. import android.app.Activity;   
  6. import android.content.ContentValues;   
  7. import android.database.Cursor;   
  8. import android.os.Bundle;   
  9. import android.widget.ListAdapter;   
  10. import android.widget.ListView;   
  11. import android.widget.SimpleCursorAdapter;   
  12. import android.widget.Toast;   
  13.   
  14. public class Test extends Activity {   
  15.     /** Called when the activity is first created. */  
  16.     ListView lv = null;   
  17.   
  18.     @Override  
  19.     public void onCreate(Bundle savedInstanceState) {   
  20.         super.onCreate(savedInstanceState);   
  21.         setContentView(R.layout.main);   
  22.         lv = (ListView) this.findViewById(R.id.ListView01);   
  23.         ContentValues cv = new ContentValues();   
  24.         cv.put(Notes.TITLE, "title1");   
  25.         cv.put(Notes.NOTE, "note1");   
  26.         this.getContentResolver().insert(Notes.CONTENT_URI, cv);   
  27.         cv.clear();   
  28.         cv.put(Notes.TITLE, "title2");   
  29.         cv.put(Notes.NOTE, "note2");   
  30.         this.getContentResolver().insert(Notes.CONTENT_URI, cv);   
  31.         this.displayNote();   
  32.     }   
  33.   
  34.     private void displayNote() {   
  35.         String[] columns = new String[] { Notes._ID, Notes.TITLE, Notes.NOTE,   
  36.                 Notes.CREATEDDATE, Notes.MODIFIEDDATE };   
  37.         Cursor c = this.managedQuery(Notes.CONTENT_URI, columns, nullnull,   
  38.                 null);   
  39.         this.startManagingCursor(c);   
  40.         if (c != null) {   
  41.             int cs = 0;   
  42.                
  43.             if(c.isBeforeFirst()){   
  44.                 cs++;   
  45.                 this.setTitle("isBeforeFirst"+cs);   
  46.             }   
  47.             if(c.moveToFirst()){   
  48.                 cs++;   
  49.                 this.setTitle("moveToFirst"+cs);   
  50.             }   
  51.             if(c.isFirst()){   
  52.                 cs++;   
  53.                 this.setTitle("isFirst"+cs);   
  54.             }   
  55.             ListAdapter adapter = new SimpleCursorAdapter(this,   
  56.                     android.R.layout.simple_list_item_2, c, new String[] {   
  57.                             Notes._ID, Notes.TITLE }, new int[] {   
  58.                             android.R.id.text1, android.R.id.text2 });   
  59.             lv.setAdapter(adapter);   
  60.   
  61.             /*  
  62.              * if (c.moveToFirst()) { this.setTitle(c.getCount()+""); String id =  
  63.              * ""; String title = ""; do { id =  
  64.              * c.getString(c.getColumnIndex(Notes._ID)); title =  
  65.              * c.getString(c.getColumnIndex(Notes.TITLE)); Toast toast =  
  66.              * Toast.makeText(this, c.getPosition()+"|ID:" + id + "|title:" +  
  67.              * title, Toast.LENGTH_LONG); toast.show(); } while  
  68.              * (c.moveToNext());  
  69.              *  }  
  70.              */  
  71.         }   
  72.     }   
  73. }  


Java代码 复制代码 收藏代码
  1. <?xml version="1.0" encoding="utf-8"?>   
  2. <manifest xmlns:android="http://schemas./apk/res/android"  
  3.     package="com.Aina.Android" android:versionCode="1"  
  4.     android:versionName="1.0">   
  5.     <application android:icon="@drawable/icon"  
  6.         android:label="@string/app_name">   
  7.         <provider android:name=".NotePadProvider"  
  8.             android:readPermission="android.permission.READ_CALENDAR"  
  9.             android:writePermission="android.permission.WRITE_CALENDAR"  
  10.             android:authorities="com.google.android.provider.notepad" />   
  11.         <activity android:name=".Test"  
  12.             android:label="@string/app_name">   
  13.             <intent-filter>   
  14.                 <action android:name="android.intent.action.MAIN" />   
  15.                 <category   
  16.                     android:name="android.intent.category.LAUNCHER" />   
  17.             </intent-filter>   
  18.             <intent-filter>   
  19.                 <data   
  20.                     android:mimeType="vnd.android.cursor.dir/vnd.google.note">   
  21.                 </data>   
  22.             </intent-filter>   
  23.             <intent-filter>   
  24.                 <data   
  25.                     android:mimeType="vnd.android.cursor.item/vnd.google.note">   
  26.                 </data>   
  27.             </intent-filter>   
  28.         </activity>   
  29.   
  30.     </application>   
  31.     
  32.   
  33. </manifest>  


2.通过ContentResolver来操作数据

Java代码 复制代码 收藏代码
  1. package com.gn.provide;   
  2.   
  3. import android.app.Activity;   
  4. import android.content.ContentValues;   
  5. import android.database.Cursor;   
  6. import android.net.Uri;   
  7. import android.os.Bundle;   
  8. import android.widget.ListAdapter;   
  9. import android.widget.ListView;   
  10. import android.widget.SimpleCursorAdapter;   
  11.   
  12. public class Tess extends Activity {   
  13.     /** Called when the activity is first created. */  
  14.     @Override  
  15.     public void onCreate(Bundle savedInstanceState) {   
  16.         super.onCreate(savedInstanceState);   
  17.         setContentView(R.layout.main);   
  18.         String uri = "content://com.google.android.provider.notepad/xixi";   
  19.         String[] columns = new String[] { "_id""title""note" };   
  20.         try {   
  21.             /*添加数据  
  22.             ContentValues cv = new ContentValues();  
  23.             cv.put("title", "new title");  
  24.             cv.put("note", "new note");  
  25.             this.getContentResolver().insert(Uri.parse(uri), cv);  
  26.             */  
  27.             /*删除数据  
  28.             int num = this.getContentResolver().delete(Uri.parse(uri), "title='new title'", null);  
  29.             */  
  30.             /*修改  
  31.             ContentValues cv = new ContentValues();  
  32.             cv.put("title", "old title");  
  33.             cv.put("note", "old note");  
  34.             long num = this.getContentResolver().update(Uri.parse(uri), cv, "_id=3", null);  
  35.             this.setTitle("num="+num);  
  36.             */  
  37.             Cursor c = this  
  38.                     .managedQuery(Uri.parse(uri), nullnullnullnull);   
  39.             // Cursor c = this.getContentResolver().query(Uri.parse(uri),   
  40.             // columns,   
  41.             // null, null, null);   
  42.             if (c == null) {   
  43.                 this.setTitle("c=null");   
  44.             } else {   
  45.                 this.startManagingCursor(c);   
  46.                 ListView lv = (ListView) this.findViewById(R.id.ListView01);   
  47.                 ListAdapter adapter = new SimpleCursorAdapter(this,   
  48.                         R.layout.simple, c, columns, new int[] { R.id.ID,   
  49.                                 R.id.title, R.id.note });   
  50.                 lv.setAdapter(adapter);   
  51.             }   
  52.         } catch (Exception ex) {   
  53.             ex.printStackTrace();   
  54.         }   
  55.     }   
  56.        
  57.        
  58. }  


Java代码 复制代码 收藏代码
  1. <?xml version="1.0" encoding="utf-8"?>   
  2. <manifest xmlns:android="http://schemas./apk/res/android"  
  3.       package="com.gn.provide"  
  4.       android:versionCode="1"  
  5.       android:versionName="1.0">   
  6.       <uses-permission android:name="android.permission.READ_CALENDAR"></uses-permission>   
  7.       <uses-permission android:name="android.permission.WRITE_CALENDAR"></uses-permission>   
  8.     <application android:icon="@drawable/icon" android:label="@string/app_name">   
  9.         <activity android:name=".Tess"  
  10.                   android:label="@string/app_name">   
  11.             <intent-filter>   
  12.                 <action android:name="android.intent.action.MAIN" />   
  13.                 <category android:name="android.intent.category.LAUNCHER" />   
  14.             </intent-filter>   
  15.         </activity>   
  16.   
  17.     </application>   
  18.   
  19.   
  20. </manifest>   

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多