android ContentProvider

ContentProvider 实现了数据间的共享,一个应用可以有多个ContentProvider ,一个ContentProvider可以有多个表结构,实例如下"

1.多个ContentProvider 



import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
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.provider.Settings;
import android.text.TextUtils;
import android.util.Log;


public class DownLoadBookmarkProvider extends ContentProvider{


    private static final String TAG = "DownLoadBookmarkProvider";
    private static final boolean LOGD =false;
    private static final String DATABASE_NAME = "download.db";
    private static final int DATABASE_VERSION = 1;
    public static final Uri uri=Uri.parse("content://com.android.user/bookmark");//com.android.user 是用于访问db的权限uri,在配置文件中要定义,同时访问的uri中要在content后面附加,用于指定这个访问路径权限
    static final String AUTHORITY = "com.android.user";
    static final String TABLE_BOOKMARK = "user";
    static final String PARAMETER_NOTIFY = "notify";
    private SQLiteOpenHelper mOpenHelper;
    
    @Override
    public boolean onCreate() {
    if(LOGD)Log.i(TAG, "=onCreate===");
        mOpenHelper = new DatabaseHelper(getContext());
    return (mOpenHelper == null) ? false : true;
    }


    @Override
    public String getType(Uri uri) {
        SqlArguments args = new SqlArguments(uri, null, null);
        if (TextUtils.isEmpty(args.where)) {
            return "vnd.android.cursor.dir/" + args.table;
        } else {
            return "vnd.android.cursor.item/" + args.table;
        }
    }
///content://com.android.launcherdemo.settings/favorites?notify=true;
    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
        SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        qb.setTables(args.table);//url.getPathSegments().get(0)


        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
        result.setNotificationUri(getContext().getContentResolver(), uri);
        return result;
    }


    @Override
    public Uri insert(Uri uri, ContentValues initialValues) {
        SqlArguments args = new SqlArguments(uri);


        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        final long rowId = db.insert(args.table, null, initialValues);
        if (rowId <= 0) return null;
        uri = ContentUris.withAppendedId(uri, rowId);
        sendNotify(uri);
        return uri;
    }


    @Override
    public int bulkInsert(Uri uri, ContentValues[] values) {
        SqlArguments args = new SqlArguments(uri);
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        db.beginTransaction();
        try {
            int numValues = values.length;
            for (int i = 0; i < numValues; i++) {
                if (db.insert(args.table, null, values[i]) < 0) return 0;
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
        sendNotify(uri);
        return values.length;
    }


    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        SqlArguments args = new SqlArguments(uri, selection, selectionArgs);


        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        int count = db.delete(args.table, args.where, args.args);
        if (count > 0) sendNotify(uri);
        return count;
    }


    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        SqlArguments args = new SqlArguments(uri, selection, selectionArgs);


        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        int count = db.update(args.table, values, args.where, args.args);
        if (count > 0) sendNotify(uri);


        return count;
    }


    private void sendNotify(Uri uri) {
        String notify = uri.getQueryParameter(PARAMETER_NOTIFY);
        if (notify == null || "true".equals(notify)) {
            getContext().getContentResolver().notifyChange(uri, null);
        }
    }


    private static class DatabaseHelper extends SQLiteOpenHelper {
        private final Context mContext;
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            mContext = context;
        }


        @Override
        public void onCreate(SQLiteDatabase db) {
            if (LOGD) Log.d(TAG, "creating new launcher database");
            
            db.execSQL("CREATE TABLE bookmark (" +
                    "_id INTEGER PRIMARY KEY," +
                    "title TEXT" +
                    ");");


            // Database was just created, so wipe any previous widgets
            if (!convertDatabase(db)) {
            }
        }


        private boolean convertDatabase(SQLiteDatabase db) {
            if (LOGD) Log.d(TAG, "converting database from an older format, but not onUpgrade");
            boolean converted = false;


            final Uri uri = Uri.parse("content://" + Settings.AUTHORITY +
                    "/old_favorites?notify=true");
            final ContentResolver resolver = mContext.getContentResolver();
            Cursor cursor = null;


            try {
                cursor = resolver.query(uri, null, null, null, null);
            } catch (Exception e) {
           // Ignore
            }
            // We already have a favorites database in the old provider
            if (cursor != null && cursor.getCount() > 0) {
                try {
                    converted = copyFromCursor(db, cursor) > 0;
                } finally {
                    cursor.close();
                }


                if (converted) {
                    resolver.delete(uri, null, null);
                }
            }
            return converted;
        }


        private int copyFromCursor(SQLiteDatabase db, Cursor c) {
           /* final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
           
            ContentValues[] rows = new ContentValues[c.getCount()];
            int i = 0;
            while (c.moveToNext()) {
                ContentValues values = new ContentValues(c.getColumnCount());
                values.put(LauncherSettings.Favorites._ID, c.getLong(idIndex));
                rows[i++] = values;
            }


            db.beginTransaction();
            int total = 0;
            try {
                int numValues = rows.length;
                for (i = 0; i < numValues; i++) {
                    if (db.insert(TABLE_FAVORITES, null, rows[i]) < 0) {
                        return 0;
                    } else {
                        total++;
                    }
                }
                db.setTransactionSuccessful();
            } finally {
                db.endTransaction();
            }


            return total;*/
        return 0;
        }


        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            if (LOGD) Log.d(TAG, "onUpgrade triggered");
            int version = oldVersion;
            if (version != DATABASE_VERSION) {
                Log.w(TAG, "Destroying all old data.");
                db.execSQL("DROP TABLE IF EXISTS " + TABLE_BOOKMARK);
                onCreate(db);
            }
        }
    }


    static class SqlArguments {
        public final String table;
        public final String where;
        public final String[] args;


        SqlArguments(Uri url, String where, String[] args) {
            if (url.getPathSegments().size() == 1) {
                this.table = url.getPathSegments().get(0);
                this.where = where;
                this.args = args;
            } else if (url.getPathSegments().size() != 2) {
                throw new IllegalArgumentException("Invalid URI: " + url);
            } else if (!TextUtils.isEmpty(where)) {
                throw new UnsupportedOperationException("WHERE clause not supported: " + url);
            } else {
                this.table = url.getPathSegments().get(0);///content://com.android.launcherdemo.settings/favorites?notify=true;
                this.where = "_id=" + ContentUris.parseId(url);                
                this.args = null;
            }
        }


        SqlArguments(Uri url) {
            if (url.getPathSegments().size() == 1) {
                table = url.getPathSegments().get(0);
                where = null;
                args = null;
            } else {
                throw new IllegalArgumentException("Invalid URI: " + url);
            }
        }
    }


}





第二个Contentprovider 





import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
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.provider.Settings;
import android.text.TextUtils;
import android.util.Log;


public class PlauginProvider extends ContentProvider{
 private static final String TAG = "PlauginProvider";
   private static final boolean LOGD =true;
   private static final String DATABASE_NAME = "email.db";
   private static final int DATABASE_VERSION = 1;
   public static final Uri uri=Uri.parse("content://com.android.email/email");//最后的email是访问的表 com.android.email是访问的路径权限,在配置文件中要定义
   static final String AUTHORITY = "com.android.email";
   static final String TABLE_PLAUGIN= "emails";
   static final String PARAMETER_NOTIFY = "notify";
   private SQLiteOpenHelper mOpenHelper;
   
   @Override
   public boolean onCreate() {
    if(LOGD)Log.i(TAG, "=onCreate===");
       mOpenHelper = new DatabaseHelper(getContext());
  return (mOpenHelper == null) ? false : true;
   }


   @Override
   public String getType(Uri uri) {
       SqlArguments args = new SqlArguments(uri, null, null);
       if (TextUtils.isEmpty(args.where)) {
           return "vnd.android.cursor.dir/" + args.table;
       } else {
           return "vnd.android.cursor.item/" + args.table;
       }
   }
///content://com.android.launcherdemo.settings/favorites?notify=true;
   @Override
   public Cursor query(Uri uri, String[] projection, String selection,
           String[] selectionArgs, String sortOrder) {
       SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
       SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
       qb.setTables(args.table);//url.getPathSegments().get(0)


       SQLiteDatabase db = mOpenHelper.getWritableDatabase();
       Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
       result.setNotificationUri(getContext().getContentResolver(), uri);
       return result;
   }


   @Override
   public Uri insert(Uri uri, ContentValues initialValues) {
       SqlArguments args = new SqlArguments(uri);


       SQLiteDatabase db = mOpenHelper.getWritableDatabase();
       final long rowId = db.insert(args.table, null, initialValues);
       if (rowId <= 0) return null;
       uri = ContentUris.withAppendedId(uri, rowId);
       sendNotify(uri);
       return uri;
   }


   @Override
   public int bulkInsert(Uri uri, ContentValues[] values) {
       SqlArguments args = new SqlArguments(uri);
       SQLiteDatabase db = mOpenHelper.getWritableDatabase();
       db.beginTransaction();
       try {
           int numValues = values.length;
           for (int i = 0; i < numValues; i++) {
               if (db.insert(args.table, null, values[i]) < 0) return 0;
           }
           db.setTransactionSuccessful();
       } finally {
           db.endTransaction();
       }
       sendNotify(uri);
       return values.length;
   }


   @Override
   public int delete(Uri uri, String selection, String[] selectionArgs) {
       SqlArguments args = new SqlArguments(uri, selection, selectionArgs);


       SQLiteDatabase db = mOpenHelper.getWritableDatabase();
       int count = db.delete(args.table, args.where, args.args);
       if (count > 0) sendNotify(uri);
       return count;
   }


   @Override
   public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
       SqlArguments args = new SqlArguments(uri, selection, selectionArgs);


       SQLiteDatabase db = mOpenHelper.getWritableDatabase();
       int count = db.update(args.table, values, args.where, args.args);
       if (count > 0) sendNotify(uri);


       return count;
   }


   private void sendNotify(Uri uri) {
       String notify = uri.getQueryParameter(PARAMETER_NOTIFY);
       if (notify == null || "true".equals(notify)) {
           getContext().getContentResolver().notifyChange(uri, null);
       }
   }


   private static class DatabaseHelper extends SQLiteOpenHelper {
       private final Context mContext;
       DatabaseHelper(Context context) {
           super(context, DATABASE_NAME, null, DATABASE_VERSION);
           mContext = context;
       }


       @Override
       public void onCreate(SQLiteDatabase db) {
           if (LOGD) Log.d(TAG, "creating new plaugin database");
           
           db.execSQL("CREATE TABLE plaugin (" +
                   "_id INTEGER," +
                   "title TEXT" +
                   ");");


           // Database was just created, so wipe any previous widgets
           if (!convertDatabase(db)) {
           }
       }


       private boolean convertDatabase(SQLiteDatabase db) {
           if (LOGD) Log.d(TAG, "converting database from an older format, but not onUpgrade");
           boolean converted = false;


           final Uri uri = Uri.parse("content://" + Settings.AUTHORITY +
                   "/old_favorites?notify=true");
           final ContentResolver resolver = mContext.getContentResolver();
           Cursor cursor = null;


           try {
               cursor = resolver.query(uri, null, null, null, null);
           } catch (Exception e) {
           // Ignore
           }
           // We already have a favorites database in the old provider
           if (cursor != null && cursor.getCount() > 0) {
               try {
                   converted = copyFromCursor(db, cursor) > 0;
               } finally {
                   cursor.close();
               }


               if (converted) {
                   resolver.delete(uri, null, null);
               }
           }
           return converted;
       }


       private int copyFromCursor(SQLiteDatabase db, Cursor c) {
          /* final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
          
           ContentValues[] rows = new ContentValues[c.getCount()];
           int i = 0;
           while (c.moveToNext()) {
               ContentValues values = new ContentValues(c.getColumnCount());
               values.put(LauncherSettings.Favorites._ID, c.getLong(idIndex));
               rows[i++] = values;
           }


           db.beginTransaction();
           int total = 0;
           try {
               int numValues = rows.length;
               for (i = 0; i < numValues; i++) {
                   if (db.insert(TABLE_FAVORITES, null, rows[i]) < 0) {
                       return 0;
                   } else {
                       total++;
                   }
               }
               db.setTransactionSuccessful();
           } finally {
               db.endTransaction();
           }


           return total;*/
        return 0;
       }


       @Override
       public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
           if (LOGD) Log.d(TAG, "onUpgrade triggered");
           int version = oldVersion;
           if (version != DATABASE_VERSION) {
               Log.w(TAG, "Destroying all old data.");
               db.execSQL("DROP TABLE IF EXISTS " + TABLE_PLAUGIN);
               onCreate(db);
           }
       }
   }


   static class SqlArguments {
       public final String table;
       public final String where;
       public final String[] args;


       SqlArguments(Uri url, String where, String[] args) {
           if (url.getPathSegments().size() == 1) {
               this.table = url.getPathSegments().get(0);
               this.where = where;
               this.args = args;
           } else if (url.getPathSegments().size() != 2) {
               throw new IllegalArgumentException("Invalid URI: " + url);
           } else if (!TextUtils.isEmpty(where)) {
               throw new UnsupportedOperationException("WHERE clause not supported: " + url);
           } else {
               this.table = url.getPathSegments().get(0);///content://com.android.launcherdemo.settings/favorites?notify=true;
               this.where = "_id=" + ContentUris.parseId(url);                
               this.args = null;
           }
       }


       SqlArguments(Uri url) {
           if (url.getPathSegments().size() == 1) {
               table = url.getPathSegments().get(0);
               where = null;
               args = null;
           } else {
               throw new IllegalArgumentException("Invalid URI: " + url);
           }
       }
   }


}



配置文件:



        <provider android:name=".DownLoadBookmarkProvider" android:authorities="com.aqndroid.user"/> //访问文件的路径的权限
         <provider android:name=".PlauginProvider" android:authorities="com.android.email"/>


2.一个ContentProvider创建多个表结构

package com.android.test.broadcast;


import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;


public class MyContentProvider extends ContentProvider{
private static final boolean LOGD =false;
private SQLiteDatabase mySqlDB;
private DatabaseHelper mDBHelpler;
private static final String DATABASE_NAME = "Users.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "contcats";
private static final String TABLE_USER = "user";
private static final String TAG ="MyContentProvider";
public static final String author="hello";
public static final  Uri ContentUserUri=Uri.parse("content://hello/user");//user表访问的路径,hello控制路径访问权限,在配置文件中要定义
public static final  Uri ContentContactUri=Uri.parse("content://hello/contcats");//contacts表访问的路径
   static final String PARAMETER_NOTIFY = "notify";
   private SQLiteOpenHelper mOpenHelper;
   private static class DatabaseHelper extends SQLiteOpenHelper {
       private final Context mContext;
       DatabaseHelper(Context context) {
           super(context, DATABASE_NAME, null, DATABASE_VERSION);
           mContext = context;
       }


       @Override
       public void onCreate(SQLiteDatabase db) {
           if (LOGD) Log.d(TAG, "creating new launcher database");
           
      db.execSQL("Create table " + TABLE_NAME + "( _id INTEGER PRIMARY KEY AUTOINCREMENT, CONTACTS_NAME TEXT);");
    db.execSQL("Create table " + TABLE_USER + "( _id INTEGER PRIMARY KEY AUTOINCREMENT, age INTEGER);");


           // Database was just created, so wipe any previous widgets
           if (!convertDatabase(db)) {
           }
       }


       private boolean convertDatabase(SQLiteDatabase db) {
           if (LOGD) Log.d(TAG, "converting database from an older format, but not onUpgrade");
           boolean converted = false;


           final Uri uri = Uri.parse("content://" + Settings.AUTHORITY +
                   "/old_favorites?notify=true");
           final ContentResolver resolver = mContext.getContentResolver();
           Cursor cursor = null;


           try {
               cursor = resolver.query(uri, null, null, null, null);
           } catch (Exception e) {
           // Ignore
           }
           // We already have a favorites database in the old provider
           if (cursor != null && cursor.getCount() > 0) {
               try {
                   converted = copyFromCursor(db, cursor) > 0;
               } finally {
                   cursor.close();
               }


               if (converted) {
                   resolver.delete(uri, null, null);
               }
           }
           return converted;
       }


       private int copyFromCursor(SQLiteDatabase db, Cursor c) {
          /* final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
          
           ContentValues[] rows = new ContentValues[c.getCount()];
           int i = 0;
           while (c.moveToNext()) {
               ContentValues values = new ContentValues(c.getColumnCount());
               values.put(LauncherSettings.Favorites._ID, c.getLong(idIndex));
               rows[i++] = values;
           }


           db.beginTransaction();
           int total = 0;
           try {
               int numValues = rows.length;
               for (i = 0; i < numValues; i++) {
                   if (db.insert(TABLE_FAVORITES, null, rows[i]) < 0) {
                       return 0;
                   } else {
                       total++;
                   }
               }
               db.setTransactionSuccessful();
           } finally {
               db.endTransaction();
           }


           return total;*/
        return 0;
       }


       @Override
       public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
           if (LOGD) Log.d(TAG, "onUpgrade triggered");
           int version = oldVersion;
           if (version != DATABASE_VERSION) {
               Log.w(TAG, "Destroying all old data.");
               db.execSQL("DROP TABLE IF EXISTS user");
               db.execSQL("DROP TABLE IF EXISTS contacts");
               onCreate(db);
           }
       }
   }


@Override
   public boolean onCreate() {
    if(LOGD)Log.i(TAG, "=onCreate===");
       mOpenHelper = new DatabaseHelper(getContext());
  return (mOpenHelper == null) ? false : true;
   }


   @Override
   public String getType(Uri uri) {
       SqlArguments args = new SqlArguments(uri, null, null);
       if (TextUtils.isEmpty(args.where)) {
           return "vnd.android.cursor.dir/" + args.table;
       } else {
           return "vnd.android.cursor.item/" + args.table;
       }
   }
///content://com.android.launcherdemo.settings/favorites?notify=true;
   @Override
   public Cursor query(Uri uri, String[] projection, String selection,
           String[] selectionArgs, String sortOrder) {
       SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
       SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
       qb.setTables(args.table);//url.getPathSegments().get(0)


       SQLiteDatabase db = mOpenHelper.getWritableDatabase();
       Cursor result = qb.query(db, projection, args.where, args.args, null, null, sortOrder);
       result.setNotificationUri(getContext().getContentResolver(), uri);
       return result;
   }


   @Override
   public Uri insert(Uri uri, ContentValues initialValues) {
       SqlArguments args = new SqlArguments(uri);


       SQLiteDatabase db = mOpenHelper.getWritableDatabase();
       final long rowId = db.insert(args.table, null, initialValues);
       if (rowId <= 0) return null;
       uri = ContentUris.withAppendedId(uri, rowId);
       sendNotify(uri);
       return uri;
   }


   @Override
   public int bulkInsert(Uri uri, ContentValues[] values) {
       SqlArguments args = new SqlArguments(uri);
       SQLiteDatabase db = mOpenHelper.getWritableDatabase();
       db.beginTransaction();
       try {
           int numValues = values.length;
           for (int i = 0; i < numValues; i++) {
               if (db.insert(args.table, null, values[i]) < 0) return 0;
           }
           db.setTransactionSuccessful();
       } finally {
           db.endTransaction();
       }
       sendNotify(uri);
       return values.length;
   }


   @Override
   public int delete(Uri uri, String selection, String[] selectionArgs) {
       SqlArguments args = new SqlArguments(uri, selection, selectionArgs);


       SQLiteDatabase db = mOpenHelper.getWritableDatabase();
       int count = db.delete(args.table, args.where, args.args);
       if (count > 0) sendNotify(uri);
       return count;
   }


   @Override
   public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
       SqlArguments args = new SqlArguments(uri, selection, selectionArgs);


       SQLiteDatabase db = mOpenHelper.getWritableDatabase();
       int count = db.update(args.table, values, args.where, args.args);
       if (count > 0) sendNotify(uri);


       return count;
   }


   private void sendNotify(Uri uri) {
       String notify = uri.getQueryParameter(PARAMETER_NOTIFY);
       if (notify == null || "true".equals(notify)) {
           getContext().getContentResolver().notifyChange(uri, null);
       }
   }




   static class SqlArguments {
       public final String table;
       public final String where;
       public final String[] args;


       SqlArguments(Uri url, String where, String[] args) {
           if (url.getPathSegments().size() == 1) {
               this.table = url.getPathSegments().get(0);
               this.where = where;
               this.args = args;
           } else if (url.getPathSegments().size() != 2) {
               throw new IllegalArgumentException("Invalid URI: " + url);
           } else if (!TextUtils.isEmpty(where)) {
               throw new UnsupportedOperationException("WHERE clause not supported: " + url);
           } else {
               this.table = url.getPathSegments().get(0); ///content://com.android.launcherdemo.settings/favorites?notify=true;
               this.where = "_id=" + ContentUris.parseId(url);                
               this.args = null;
           }
       }


       SqlArguments(Uri url) {
           if (url.getPathSegments().size() == 1) {
               table = url.getPathSegments().get(0);
               where = null;
               args = null;
           } else {
               throw new IllegalArgumentException("Invalid URI: " + url);
           }
       }
   }


}


 配置文件中定义:

 <provider android:name="com.android.test.broadcast.MyContentProvider" android:authorities="hello"></provider>

你可能感兴趣的:(android,String,table,null,Integer,database)