博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ContentProvider
阅读量:4479 次
发布时间:2019-06-08

本文共 5348 字,大约阅读时间需要 17 分钟。

我们将获得的Cursor对象交与Activity 来管理,这样Cursor对象的生命周期便能与当前的Activity自动同步,省去了自己管理Cursor。

 

public class NotesProvider extends ContentProvider {

 public static final String AUTHORITY = "com.example.android.honeypad.notesprovider";

 private static final String NOTE_MIME_TYPE = "vnd.android.cursor.item/vnd.honeypad.note";

 public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
   + "/notes");

 // The underlying database

 private SQLiteDatabase notesDB;

 // Create the constants used to differentiate between the different URI

 // requests.
 private static final int ALL_NOTES = 1;
 private static final int NOTE_ID = 2;

 private static final UriMatcher uriMatcher;

 // Allocate the UriMatcher object, where a URI ending in 'notes' will

 // correspond to a request for all notes, and 'notes' with a trailing
 // '/[rowID]' will represent a single note row.
 static {
  uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
  uriMatcher.addURI(AUTHORITY, "notes", ALL_NOTES);
  uriMatcher.addURI(AUTHORITY, "notes/#", NOTE_ID);
 }

 @Override

 public boolean onCreate() {
  NotesDatabaseHelper helper = new NotesDatabaseHelper(getContext());
  notesDB = helper.getWritableDatabase();
  return notesDB != null;
 }

 @Override

 public Cursor query(Uri uri, String[] projection, String selection,
   String[] selectionArgs, String sort) {
  SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
  qb.setTables(DATABASE_TABLE);

  // If this is a row query, limit the result set to the passed in row.

  switch (uriMatcher.match(uri)) {
  case NOTE_ID:
   qb.appendWhere(KEY_ID + "=" + uri.getPathSegments().get(1));
   break;
  default:
   break;
  }

  // Apply the query to the underlying database.

  Cursor c = qb.query(notesDB, projection, selection, selectionArgs,
    null, null, sort);

  // 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;
 }

 @Override

 public Uri insert(Uri uri, ContentValues initialValues) {
  // Insert the new row, will return the row number if
  // successful.
  long rowID = notesDB.insert(DATABASE_TABLE, "note", initialValues);

  // Return a URI to the newly inserted row on success.

  if (rowID > 0) {
   Uri newUri = ContentUris.withAppendedId(CONTENT_URI, rowID);
   getContext().getContentResolver().notifyChange(newUri, null);
   return newUri;
  }
  throw new SQLException("Failed to insert row into " + uri);
 }

 @Override

 public int delete(Uri uri, String where, String[] whereArgs) {
  int count;

  switch (uriMatcher.match(uri)) {

  case ALL_NOTES:
   count = notesDB.delete(DATABASE_TABLE, where, whereArgs);
   break;

  case NOTE_ID:

   String segment = uri.getPathSegments().get(1);
   StringBuilder whereClause = new StringBuilder(KEY_ID).append("=")
     .append(segment);
   if (!TextUtils.isEmpty(where)) {
    whereClause.append(" AND (").append(where).append(")");
   }

   count = notesDB.delete(DATABASE_TABLE, whereClause.toString(),

     whereArgs);
   break;

  default:

   throw new IllegalArgumentException("Unsupported URI: " + uri);
  }

  getContext().getContentResolver().notifyChange(uri, null);

  return count;
 }

 @Override

 public int update(Uri uri, ContentValues values, String where,
   String[] whereArgs) {
  int count;
  switch (uriMatcher.match(uri)) {
  case ALL_NOTES:
   count = notesDB.update(DATABASE_TABLE, values, where, whereArgs);
   break;

  case NOTE_ID:

   String segment = uri.getPathSegments().get(1);
   StringBuilder whereClause = new StringBuilder(KEY_ID).append("=")
     .append(segment);
   if (!TextUtils.isEmpty(where)) {
    whereClause.append(" AND (").append(where).append(")");
   }
   count = notesDB.update(DATABASE_TABLE, values,
     whereClause.toString(), whereArgs);
   break;

  default:

   throw new IllegalArgumentException("Unknown URI " + uri);
  }

  getContext().getContentResolver().notifyChange(uri, null);

  return count;
 }

 @Override

 public String getType(Uri uri) {
  switch (uriMatcher.match(uri)) {
  case ALL_NOTES:
   return "vnd.android.cursor.dir/vnd.honeypad.notes";
  case NOTE_ID:
   return NOTE_MIME_TYPE;
  default:
   throw new IllegalArgumentException("Unsupported URI: " + uri);
  }
 }

 // column names

 public static final String KEY_ID = "_id";
 public static final String KEY_TITLE = "title";
 public static final String KEY_BODY = "body";
 
 // column indexes
 public static final int ID_COLUMN = 0;
 public static final int TITLE_COLUMN = 1;
 public static final int BODY_COLUMN = 2;
 
 private static final String TAG = "NotesDbAdapter";

 private static final String DATABASE_NAME = "honeypad.db";

 private static final String DATABASE_TABLE = "notes";
 private static final int DATABASE_VERSION = 1;

 /**

  * Database creation sql statement
  */
 private static final String DATABASE_CREATE = String.format("create table %s (%s integer primary key autoincrement, %s text not null, %s text not null);",
   DATABASE_TABLE, KEY_ID, KEY_TITLE, KEY_BODY);

 private static class NotesDatabaseHelper extends SQLiteOpenHelper {

  NotesDatabaseHelper(Context context) {

   super(context, DATABASE_NAME, null, DATABASE_VERSION);
  }

  @Override

  public void onCreate(SQLiteDatabase db) {

   db.execSQL(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 notes");
   onCreate(db);
  }
 }

 }

转载于:https://www.cnblogs.com/ljchaction/archive/2012/04/10/2441318.html

你可能感兴趣的文章
UIResponder学习
查看>>
redis 主从服务器
查看>>
设计模式完结(6)--适配器模式----不兼容结构的协调
查看>>
关于Aspose强大的应用--EXECL
查看>>
课堂final发布
查看>>
解锁scott用户
查看>>
多态的理解
查看>>
AspNet Core 发布到Linux系统和发布IIS 注意项
查看>>
Windows添加.NET Framework 3.0 NetFx3 失败 - 状态为:0x800f0950
查看>>
隐藏显示终端的光标(shell echo,linux c printf)
查看>>
SQL Server 存储过程
查看>>
JSP 标准标签库(JSTL)(JSP Standard Tag Library)
查看>>
导入项目遇到的问题: Some projects cannot be imported because they already exist in the workspace....
查看>>
华为:字符集合
查看>>
window10 家庭版 添加Hyper-V虚拟机
查看>>
1020. 月饼 (25)
查看>>
《小学生四则运算出题软件》个人项目总结
查看>>
QFTP走了以后QNetworkAccessManager出现了
查看>>
flex 中embed 的用法
查看>>
安装vuecli和使用elememtUi
查看>>