android数据库操作(ContentProvider)
2017-08-11 08:02
507 查看
自定义的ContentProvider在android系统初始化过程中就会被加载启动,从而实现数据库的初始化操作,ContentProvider通过一个URI来联系数据库中的表,通过getContentResolver()来访问数据库,可以通过ContentValues来修改表中的数据等。ContentProvider创建数据库等一系列初始化操作如下:
public class MediaProvider extends ContentProvider {
public static final Uri MUSIC_CONTENT_URI = Uri
.parse("content://ru.org.piaozhiye.MediaProvider/musics");
public static final Uri VIDEO_CONTENT_URI = Uri
.parse("content://ru.org.piaozhiye.MediaProvider/videos");
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
return null;
}
@Override
public Uri insert(Uri _uri, ContentValues values) {
if (_uri.equals(MUSIC_CONTENT_URI)) {
// Insert the new row, will return the row number if
// successful.
long rowID = DB.insert(MUSIC_TABLE, "music", values);
// Return a URI to the newly inserted row on success.
if (rowID > 0) {
Uri uri = ContentUris.withAppendedId(MUSIC_CONTENT_URI, rowID);
getContext().getContentResolver().notifyChange(uri, null);
return uri;
}
throw new SQLException("Failed to insert row into " + _uri);
} else if (_uri.equals(VIDEO_CONTENT_URI)) {
// Insert the new row, will return the row number if
// successful.
long rowID = DB.insert(VIDEO_TABLE, "video", values);
// Return a URI to the newly inserted row on success.
if (rowID > 0) {
Uri uri = ContentUris.withAppendedId(MUSIC_CONTENT_URI, rowID);
getContext().getContentResolver().notifyChange(uri, null);
return uri;
}
throw new SQLException("Failed to insert row into " + _uri);
} else
return null;
}
@Override
public boolean onCreate() {
Context context = getContext();
MediaDatabaseHelper dbHelper = new MediaDatabaseHelper(context,
DATABASE_NAME, null, DATABASE_VERSION);
DB = dbHelper.getWritableDatabase();
Log.e(TAG, Environment.getExternalStorageDirectory().toString());
return (DB == null) ? false : true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sort) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
if (uri.equals(MUSIC_CONTENT_URI)) {
qb.setTables(MUSIC_TABLE);
// If this is a row query, limit the result set to the passed in
// row.
switch (uriMatcher.match(uri)) {
case MUSIC_ID:
qb.appendWhere(KEY_ID + "=" + uri.getPathSegments().get(1));
break;
default:
break;
}
// If no sort order is specified sort by date / time
String orderBy;
if (TextUtils.isEmpty(sort)) {
orderBy = KEY_DATE;
} else {
orderBy = sort;
}
// Apply the query to the underlying database.
Cursor c = qb.query(DB, projection, selection, selectionArgs, null,
null, orderBy);
// Register the contexts ContentResolver to be notified if
// the cursor result set changes.
c.setNotificationUri(getContext().getContentResolver(), uri);
// Return a cursor to the query result.
return c;
} else if (uri.equals(VIDEO_CONTENT_URI)) {
qb.setTables(VIDEO_TABLE);
// If this is a row query, limit the result set to the passed in
// row.
switch (uriMatcher.match(uri)) {
case VIDEO_ID:
qb.appendWhere(KEY_ID + "=" + uri.getPathSegments().get(1));
break;
default:
break;
}
// If no sort order is specified sort by date / time
String orderBy;
if (TextUtils.isEmpty(sort)) {
orderBy = KEY_DATE;
} else {
orderBy = sort;
}
// Apply the query to the underlying database.
Cursor c = qb.query(DB, projection, selection, selectionArgs, null,
null, orderBy);
// Register the contexts ContentResolver to be notified if
// the cursor result set changes.
c.setNotificationUri(getContext().getContentResolver(), uri);
// Return a cursor to the query result.
return c;
}
return null;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
// TODO Auto-generated method stub
return 0;
}
// Create the constants used to differentiate between the different URI
// requests.
private static final int MUSICS = 1;
private static final int MUSIC_ID = 2;
private static final int VIDEDOS = 3;
private static final int VIDEO_ID = 4;
private static final UriMatcher uriMatcher;
// Allocate the UriMatcher object, where a URI ending in 'earthquakes' will
// correspond to a request for all earthquakes, and 'earthquakes' with a
// trailing '/[rowID]' will represent a single earthquake row.
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI("ru.org.piaozhiye.MediaProvider", "musics", MUSICS);
uriMatcher.addURI("ru.org.piaozhiye.MediaProvider", "musics/#",
MUSIC_ID);
uriMatcher.addURI("ru.org.piaozhiye.MediaProvider", "videos", VIDEDOS);
uriMatcher.addURI("ru.org.piaozhiye.MediaProvider", "videos/#",
VIDEO_ID);
}
// The underlying database
private SQLiteDatabase DB;
private static final String TAG = "MediaProvider";
private static final String DATABASE_NAME = "media.db";
private static final int DATABASE_VERSION = 2;
private static final String MUSIC_TABLE = "musics";
private static final String VIDEO_TABLE = "videos";
// AUDIO Column Names
public static final String KEY_ID = "_id";
public static final String KEY_PATH = "path";
public static final String KEY_TITLE = "title";
public static final String KEY_SIZE = "size";
public static final String KEY_DISPLAY_NAME = "displayname";
public static final String KEY_LASTPOSITON = "lastposition";
public static final String KEY_DURATION = "duration";
public static final String KEY_DATE = "date";
public static final String KEY_ARTIST = "artist";
public static final String KEY_ALBUM_NAME = "album";
public static final String KEY_ALBUM_ID = "albumId";
public static final String KEY_ALBUM_PATH = "albumpath";
public static final String KEY_ALBUM_ART = "albumart";
public static final String KEY_YEAR = "year";
public static final String KEY_TYPE = "type";
public static final String KEY_TRACK = "track";
public static final String KEY_RESULOTION = "resulotion";
// Helper class for opening, creating, and managing database version control
private static class MediaDatabaseHelper extends SQLiteOpenHelper {
private static final String MUSIC_DATABASE_CREATE = "create table "
+ MUSIC_TABLE + " (" + KEY_ID
+ " integer primary key autoincrement, " + KEY_PATH
+ " TEXT, "
+ KEY_TITLE
+ " TEXT, "
// + KEY_ALBUM_ID + " TEXT, "
+ KEY_ALBUM_NAME + " TEXT, " + KEY_DURATION + " TEXT, "
+ KEY_ARTIST + " TEXT, " + KEY_DATE + " TEXT, " + KEY_SIZE
+ " TEXT, " + KEY_TRACK + " TEXT, " + KEY_YEAR + " TEXT, "
+ KEY_LASTPOSITON + " TEXT, " + KEY_TYPE + " TEXT" + ");";
private static final String VIDEO_DATABASE_CREATE = "create table "
+ VIDEO_TABLE + " (" + KEY_ID
+ " integer primary key autoincrement, " + KEY_PATH + " TEXT, "
+ KEY_DISPLAY_NAME + " TEXT, " + KEY_DURATION + " TEXT, "
+ KEY_DATE + " TEXT, " + KEY_SIZE + " TEXT, " + KEY_RESULOTION
+ " TEXT, " + KEY_LASTPOSITON + " TEXT" + ");";
public MediaDatabaseHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
// SQLiteDatabase.openOrCreateDatabase(DBPATH, null);
db.execSQL(MUSIC_DATABASE_CREATE);
db.execSQL(VIDEO_DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + MUSIC_TABLE);
db.execSQL("DROP TABLE IF EXISTS " + VIDEO_TABLE);
onCreate(db);
}
}
}
对应的查询数据库操作伪代码如下:
String[] str = {"date", "package", "id"} //查询字段
String[] params = [tStart, tEnd];
Cursor cursor = getContentResolver().query(uri// 查询对应的uri,
str //需要查询的字段
“date” + “between ? and ?” //查询条件
params //查询条件中的参数
null //排序);
public class MediaProvider extends ContentProvider {
public static final Uri MUSIC_CONTENT_URI = Uri
.parse("content://ru.org.piaozhiye.MediaProvider/musics");
public static final Uri VIDEO_CONTENT_URI = Uri
.parse("content://ru.org.piaozhiye.MediaProvider/videos");
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
return null;
}
@Override
public Uri insert(Uri _uri, ContentValues values) {
if (_uri.equals(MUSIC_CONTENT_URI)) {
// Insert the new row, will return the row number if
// successful.
long rowID = DB.insert(MUSIC_TABLE, "music", values);
// Return a URI to the newly inserted row on success.
if (rowID > 0) {
Uri uri = ContentUris.withAppendedId(MUSIC_CONTENT_URI, rowID);
getContext().getContentResolver().notifyChange(uri, null);
return uri;
}
throw new SQLException("Failed to insert row into " + _uri);
} else if (_uri.equals(VIDEO_CONTENT_URI)) {
// Insert the new row, will return the row number if
// successful.
long rowID = DB.insert(VIDEO_TABLE, "video", values);
// Return a URI to the newly inserted row on success.
if (rowID > 0) {
Uri uri = ContentUris.withAppendedId(MUSIC_CONTENT_URI, rowID);
getContext().getContentResolver().notifyChange(uri, null);
return uri;
}
throw new SQLException("Failed to insert row into " + _uri);
} else
return null;
}
@Override
public boolean onCreate() {
Context context = getContext();
MediaDatabaseHelper dbHelper = new MediaDatabaseHelper(context,
DATABASE_NAME, null, DATABASE_VERSION);
DB = dbHelper.getWritableDatabase();
Log.e(TAG, Environment.getExternalStorageDirectory().toString());
return (DB == null) ? false : true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sort) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
if (uri.equals(MUSIC_CONTENT_URI)) {
qb.setTables(MUSIC_TABLE);
// If this is a row query, limit the result set to the passed in
// row.
switch (uriMatcher.match(uri)) {
case MUSIC_ID:
qb.appendWhere(KEY_ID + "=" + uri.getPathSegments().get(1));
break;
default:
break;
}
// If no sort order is specified sort by date / time
String orderBy;
if (TextUtils.isEmpty(sort)) {
orderBy = KEY_DATE;
} else {
orderBy = sort;
}
// Apply the query to the underlying database.
Cursor c = qb.query(DB, projection, selection, selectionArgs, null,
null, orderBy);
// Register the contexts ContentResolver to be notified if
// the cursor result set changes.
c.setNotificationUri(getContext().getContentResolver(), uri);
// Return a cursor to the query result.
return c;
} else if (uri.equals(VIDEO_CONTENT_URI)) {
qb.setTables(VIDEO_TABLE);
// If this is a row query, limit the result set to the passed in
// row.
switch (uriMatcher.match(uri)) {
case VIDEO_ID:
qb.appendWhere(KEY_ID + "=" + uri.getPathSegments().get(1));
break;
default:
break;
}
// If no sort order is specified sort by date / time
String orderBy;
if (TextUtils.isEmpty(sort)) {
orderBy = KEY_DATE;
} else {
orderBy = sort;
}
// Apply the query to the underlying database.
Cursor c = qb.query(DB, projection, selection, selectionArgs, null,
null, orderBy);
// Register the contexts ContentResolver to be notified if
// the cursor result set changes.
c.setNotificationUri(getContext().getContentResolver(), uri);
// Return a cursor to the query result.
return c;
}
return null;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
// TODO Auto-generated method stub
return 0;
}
// Create the constants used to differentiate between the different URI
// requests.
private static final int MUSICS = 1;
private static final int MUSIC_ID = 2;
private static final int VIDEDOS = 3;
private static final int VIDEO_ID = 4;
private static final UriMatcher uriMatcher;
// Allocate the UriMatcher object, where a URI ending in 'earthquakes' will
// correspond to a request for all earthquakes, and 'earthquakes' with a
// trailing '/[rowID]' will represent a single earthquake row.
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI("ru.org.piaozhiye.MediaProvider", "musics", MUSICS);
uriMatcher.addURI("ru.org.piaozhiye.MediaProvider", "musics/#",
MUSIC_ID);
uriMatcher.addURI("ru.org.piaozhiye.MediaProvider", "videos", VIDEDOS);
uriMatcher.addURI("ru.org.piaozhiye.MediaProvider", "videos/#",
VIDEO_ID);
}
// The underlying database
private SQLiteDatabase DB;
private static final String TAG = "MediaProvider";
private static final String DATABASE_NAME = "media.db";
private static final int DATABASE_VERSION = 2;
private static final String MUSIC_TABLE = "musics";
private static final String VIDEO_TABLE = "videos";
// AUDIO Column Names
public static final String KEY_ID = "_id";
public static final String KEY_PATH = "path";
public static final String KEY_TITLE = "title";
public static final String KEY_SIZE = "size";
public static final String KEY_DISPLAY_NAME = "displayname";
public static final String KEY_LASTPOSITON = "lastposition";
public static final String KEY_DURATION = "duration";
public static final String KEY_DATE = "date";
public static final String KEY_ARTIST = "artist";
public static final String KEY_ALBUM_NAME = "album";
public static final String KEY_ALBUM_ID = "albumId";
public static final String KEY_ALBUM_PATH = "albumpath";
public static final String KEY_ALBUM_ART = "albumart";
public static final String KEY_YEAR = "year";
public static final String KEY_TYPE = "type";
public static final String KEY_TRACK = "track";
public static final String KEY_RESULOTION = "resulotion";
// Helper class for opening, creating, and managing database version control
private static class MediaDatabaseHelper extends SQLiteOpenHelper {
private static final String MUSIC_DATABASE_CREATE = "create table "
+ MUSIC_TABLE + " (" + KEY_ID
+ " integer primary key autoincrement, " + KEY_PATH
+ " TEXT, "
+ KEY_TITLE
+ " TEXT, "
// + KEY_ALBUM_ID + " TEXT, "
+ KEY_ALBUM_NAME + " TEXT, " + KEY_DURATION + " TEXT, "
+ KEY_ARTIST + " TEXT, " + KEY_DATE + " TEXT, " + KEY_SIZE
+ " TEXT, " + KEY_TRACK + " TEXT, " + KEY_YEAR + " TEXT, "
+ KEY_LASTPOSITON + " TEXT, " + KEY_TYPE + " TEXT" + ");";
private static final String VIDEO_DATABASE_CREATE = "create table "
+ VIDEO_TABLE + " (" + KEY_ID
+ " integer primary key autoincrement, " + KEY_PATH + " TEXT, "
+ KEY_DISPLAY_NAME + " TEXT, " + KEY_DURATION + " TEXT, "
+ KEY_DATE + " TEXT, " + KEY_SIZE + " TEXT, " + KEY_RESULOTION
+ " TEXT, " + KEY_LASTPOSITON + " TEXT" + ");";
public MediaDatabaseHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
// SQLiteDatabase.openOrCreateDatabase(DBPATH, null);
db.execSQL(MUSIC_DATABASE_CREATE);
db.execSQL(VIDEO_DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + MUSIC_TABLE);
db.execSQL("DROP TABLE IF EXISTS " + VIDEO_TABLE);
onCreate(db);
}
}
}
对应的查询数据库操作伪代码如下:
String[] str = {"date", "package", "id"} //查询字段
String[] params = [tStart, tEnd];
Cursor cursor = getContentResolver().query(uri// 查询对应的uri,
str //需要查询的字段
“date” + “between ? and ?” //查询条件
params //查询条件中的参数
null //排序);
相关文章推荐
- Android基础之ContentProvider操作本地短信数据库
- Android中通过ContentProvider操作数据库
- ContentProvider操作数据库—一项古老的Android技术
- android 玩转ContentProvider之一--实现ContentProvider操作数据库
- android中跨项目的数据库操作ContentProvider的使用
- Android-ContentProvider数据库操作
- [Android Pro] 判断Uri对应的ContentProvider所操作的数据库u存在,及DownloadManager的暂停,继续
- android 玩转ContentProvider之一--实现ContentProvider操作数据库
- 类查找android中跨项目的数据库操作ContentProvider的使用
- Android ContentProvider之联系人数据库及操作
- Android学习---通过内容提供者(ContentProvider)操作另外一个应用私有数据库的内容
- Android数据库(SQLite)框架(5)——LitePal的修改和删除操作
- Android数据库-greenDao3.2.2初体验(下)-简单的查询和删除操作
- Android自定义数据库异步操作
- Android-SQLite商业化数据库操作
- android 操作数据库使用系统方法
- android的基础学习:SQLite存储方式以及数据库操作
- 如何将Android数据库操作通用化(一)
- Android数据库操作的简单封装
- android sqlite3:数据库操作