android数据库操作(ContentProvider)

自定义的ContentProvider在android系统初始化过程中就会被加载启动,从而实现数据库的初始化操作,ContentProvider通过一个URI来联系数据库中的表,通过getContentResolver()来访问数据库,可以通过ContentValues来修改表中的数据等。ContentProvider创建数据库等一系列初始化操作如下:

  1. public class MediaProvider extends ContentProvider {  
  2.     public static final Uri MUSIC_CONTENT_URI = Uri  
  3.             .parse("content://ru.org.piaozhiye.MediaProvider/musics");  
  4.     public static final Uri VIDEO_CONTENT_URI = Uri  
  5.             .parse("content://ru.org.piaozhiye.MediaProvider/videos");  
  6.     @Override  
  7.     public int delete(Uri uri, String selection, String[] selectionArgs) {  
  8.         // TODO Auto-generated method stub  
  9.         return 0;  
  10.     }  
  11.     @Override  
  12.     public String getType(Uri uri) {  
  13.         // TODO Auto-generated method stub  
  14.         return null;  
  15.     }  
  16.     @Override  
  17.     public Uri insert(Uri _uri, ContentValues values) {  
  18.         if (_uri.equals(MUSIC_CONTENT_URI)) {  
  19.             // Insert the new row, will return the row number if  
  20.             // successful.  
  21.             long rowID = DB.insert(MUSIC_TABLE, "music", values);  
  22.             // Return a URI to the newly inserted row on success.  
  23.             if (rowID > 0) {  
  24.                 Uri uri = ContentUris.withAppendedId(MUSIC_CONTENT_URI, rowID);  
  25.                 getContext().getContentResolver().notifyChange(uri, null);  
  26.                 return uri;  
  27.             }  
  28.             throw new SQLException("Failed to insert row into " + _uri);  
  29.         } else if (_uri.equals(VIDEO_CONTENT_URI)) {  
  30.             // Insert the new row, will return the row number if  
  31.             // successful.  
  32.             long rowID = DB.insert(VIDEO_TABLE, "video", values);  
  33.             // Return a URI to the newly inserted row on success.  
  34.             if (rowID > 0) {  
  35.                 Uri uri = ContentUris.withAppendedId(MUSIC_CONTENT_URI, rowID);  
  36.                 getContext().getContentResolver().notifyChange(uri, null);  
  37.                 return uri;  
  38.             }  
  39.             throw new SQLException("Failed to insert row into " + _uri);  
  40.         } else  
  41.             return null;  
  42.     }  
  43.     @Override  
  44.     public boolean onCreate() {  
  45.         Context context = getContext();  
  46.         MediaDatabaseHelper dbHelper = new MediaDatabaseHelper(context,  
  47.                 DATABASE_NAME, null, DATABASE_VERSION);  
  48.         DB = dbHelper.getWritableDatabase();  
  49.         Log.e(TAG, Environment.getExternalStorageDirectory().toString());  
  50.         return (DB == null) ? false : true;  
  51.     }  
  52.     @Override  
  53.     public Cursor query(Uri uri, String[] projection, String selection,  
  54.             String[] selectionArgs, String sort) {  
  55.         SQLiteQueryBuilder qb = new SQLiteQueryBuilder();  
  56.         if (uri.equals(MUSIC_CONTENT_URI)) {  
  57.             qb.setTables(MUSIC_TABLE);  
  58.             // If this is a row query, limit the result set to the passed in  
  59.             // row.  
  60.             switch (uriMatcher.match(uri)) {  
  61.             case MUSIC_ID:  
  62.                 qb.appendWhere(KEY_ID + "=" + uri.getPathSegments().get(1));  
  63.                 break;  
  64.             default:  
  65.                 break;  
  66.             }  
  67.             // If no sort order is specified sort by date / time  
  68.             String orderBy;  
  69.             if (TextUtils.isEmpty(sort)) {  
  70.                 orderBy = KEY_DATE;  
  71.             } else {  
  72.                 orderBy = sort;  
  73.             }  
  74.             // Apply the query to the underlying database.  
  75.             Cursor c = qb.query(DB, projection, selection, selectionArgs, null,  
  76.                     null, orderBy);  
  77.             // Register the contexts ContentResolver to be notified if  
  78.             // the cursor result set changes.  
  79.             c.setNotificationUri(getContext().getContentResolver(), uri);  
  80.             // Return a cursor to the query result.  
  81.             return c;  
  82.         } else if (uri.equals(VIDEO_CONTENT_URI)) {  
  83.             qb.setTables(VIDEO_TABLE);  
  84.             // If this is a row query, limit the result set to the passed in  
  85.             // row.  
  86.             switch (uriMatcher.match(uri)) {  
  87.             case VIDEO_ID:  
  88.                 qb.appendWhere(KEY_ID + "=" + uri.getPathSegments().get(1));  
  89.                 break;  
  90.             default:  
  91.                 break;  
  92.             }  
  93.             // If no sort order is specified sort by date / time  
  94.             String orderBy;  
  95.             if (TextUtils.isEmpty(sort)) {  
  96.                 orderBy = KEY_DATE;  
  97.             } else {  
  98.                 orderBy = sort;  
  99.             }  
  100.             // Apply the query to the underlying database.  
  101.             Cursor c = qb.query(DB, projection, selection, selectionArgs, null,  
  102.                     null, orderBy);  
  103.             // Register the contexts ContentResolver to be notified if  
  104.             // the cursor result set changes.  
  105.             c.setNotificationUri(getContext().getContentResolver(), uri);  
  106.             // Return a cursor to the query result.  
  107.             return c;  
  108.         }  
  109.         return null;  
  110.     }  
  111.     @Override  
  112.     public int update(Uri uri, ContentValues values, String selection,  
  113.             String[] selectionArgs) {  
  114.         // TODO Auto-generated method stub  
  115.         return 0;  
  116.     }  
  117.     // Create the constants used to differentiate between the different URI  
  118.     // requests.  
  119.     private static final int MUSICS = 1;  
  120.     private static final int MUSIC_ID = 2;  
  121.     private static final int VIDEDOS = 3;  
  122.     private static final int VIDEO_ID = 4;  
  123.     private static final UriMatcher uriMatcher;  
  124.     // Allocate the UriMatcher object, where a URI ending in 'earthquakes' will  
  125.     // correspond to a request for all earthquakes, and 'earthquakes' with a  
  126.     // trailing '/[rowID]' will represent a single earthquake row.  
  127.     static {  
  128.         uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);  
  129.         uriMatcher.addURI("ru.org.piaozhiye.MediaProvider""musics", MUSICS);  
  130.         uriMatcher.addURI("ru.org.piaozhiye.MediaProvider""musics/#",  
  131.                 MUSIC_ID);  
  132.         uriMatcher.addURI("ru.org.piaozhiye.MediaProvider""videos", VIDEDOS);  
  133.         uriMatcher.addURI("ru.org.piaozhiye.MediaProvider""videos/#",  
  134.                 VIDEO_ID);  
  135.     }  
  136.     // The underlying database  
  137.     private SQLiteDatabase DB;  
  138.     private static final String TAG = "MediaProvider";  
  139.     private static final String DATABASE_NAME = "media.db";  
  140.     private static final int DATABASE_VERSION = 2;  
  141.     private static final String MUSIC_TABLE = "musics";  
  142.     private static final String VIDEO_TABLE = "videos";  
  143.     // AUDIO Column Names  
  144.     public static final String KEY_ID = "_id";  
  145.     public static final String KEY_PATH = "path";  
  146.     public static final String KEY_TITLE = "title";  
  147.     public static final String KEY_SIZE = "size";  
  148.     public static final String KEY_DISPLAY_NAME = "displayname";  
  149.     public static final String KEY_LASTPOSITON = "lastposition";  
  150.     public static final String KEY_DURATION = "duration";  
  151.     public static final String KEY_DATE = "date";  
  152.     public static final String KEY_ARTIST = "artist";  
  153.     public static final String KEY_ALBUM_NAME = "album";  
  154.     public static final String KEY_ALBUM_ID = "albumId";  
  155.     public static final String KEY_ALBUM_PATH = "albumpath";  
  156.     public static final String KEY_ALBUM_ART = "albumart";  
  157.     public static final String KEY_YEAR = "year";  
  158.     public static final String KEY_TYPE = "type";  
  159.     public static final String KEY_TRACK = "track";  
  160.     public static final String KEY_RESULOTION = "resulotion";  
  161.     // Helper class for opening, creating, and managing database version control  
  162.     private static class MediaDatabaseHelper extends SQLiteOpenHelper {  
  163.         private static final String MUSIC_DATABASE_CREATE = "create table "  
  164.                 + MUSIC_TABLE + " (" + KEY_ID  
  165.                 + " integer primary key autoincrement, " + KEY_PATH  
  166.                 + " TEXT, "  
  167.                 + KEY_TITLE  
  168.                 + " TEXT, "  
  169.                 // + KEY_ALBUM_ID + " TEXT, "  
  170.                 + KEY_ALBUM_NAME + " TEXT, " + KEY_DURATION + " TEXT, "  
  171.                 + KEY_ARTIST + " TEXT, " + KEY_DATE + " TEXT, " + KEY_SIZE  
  172.                 + " TEXT, " + KEY_TRACK + " TEXT, " + KEY_YEAR + " TEXT, "  
  173.                 + KEY_LASTPOSITON + " TEXT, " + KEY_TYPE + " TEXT" + ");";  
  174.         private static final String VIDEO_DATABASE_CREATE = "create table "  
  175.                 + VIDEO_TABLE + " (" + KEY_ID  
  176.                 + " integer primary key autoincrement, " + KEY_PATH + " TEXT, "  
  177.                 + KEY_DISPLAY_NAME + " TEXT, " + KEY_DURATION + " TEXT, "  
  178.                 + KEY_DATE + " TEXT, " + KEY_SIZE + " TEXT, " + KEY_RESULOTION  
  179.                 + " TEXT, " + KEY_LASTPOSITON + " TEXT" + ");";  
  180.         public MediaDatabaseHelper(Context context, String name,  
  181.                 CursorFactory factory, int version) {  
  182.             super(context, name, factory, version);  
  183.         }  
  184.         @Override  
  185.         public void onCreate(SQLiteDatabase db) {  
  186.             // SQLiteDatabase.openOrCreateDatabase(DBPATH, null);  
  187.             db.execSQL(MUSIC_DATABASE_CREATE);  
  188.             db.execSQL(VIDEO_DATABASE_CREATE);  
  189.         }  
  190.         @Override  
  191.         public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  192.             Log.w(TAG, "Upgrading database from version " + oldVersion + " to "  
  193.                     + newVersion + ", which will destroy all old data");  
  194.             db.execSQL("DROP TABLE IF EXISTS " + MUSIC_TABLE);  
  195.             db.execSQL("DROP TABLE IF EXISTS " + VIDEO_TABLE);  
  196.             onCreate(db);  
  197.         }  
  198.     }  
  199. }



对应的查询数据库操作伪代码如下:

String[] str = {"date", "package", "id"} //查询字段

String[] params = [tStart, tEnd];

Cursor cursor = getContentResolver().query(uri// 查询对应的uri,

str //需要查询的字段

“date” + “between ? and ?” //查询条件

 params //查询条件中的参数

null //排序);




猜你喜欢

转载自blog.csdn.net/liangtianmeng/article/details/76100972