Content Resolver简介

每个应用程序都有一个ContentResolver实例,通过getContentResolver()方法可以获取:

ContentResolver cr = getContentResolver();

与Content Provider对应,Content Resolver用于使用Content Provider发布的数据。使用ContentResolver查询ConentProvider提供的数据:

// Get the Content Resolver.
ContentResolver cr = getContentResolver();
// Specify the result column projection. Return the minimum set of columns required to satisfy your requirements.
String[] result_columns = new String[] {
  MyHoardContentProvider.KEY_ID,
  MyHoardContentProvider.KEY_GOLD_HOARD_ACCESSIBLE_COLUMN,
  MyHoardContentProvider.KEY_GOLD_HOARDED_COLUMN };
// Specify the where clause that will limit your results.
String where = MyHoardContentProvider.KEY_GOLD_HOARD_ACCESSIBLE_COLUMN + “=” + 1;
// Replace these with valid SQL statements as necessary.
String whereArgs[] = null;
String order = null;
// Return the specified rows.
Cursor resultCursor = cr.query(MyHoardContentProvider.CONTENT_URI, result_columns, where, whereArgs, order);

从Cursor中解析数据的方法和上一篇博文中介绍的一样,首先要移动到指定行,然后从指定列中获取对应类型的数据:

float largestHoard = 0f;
String hoardName = “No Hoards”;
// Find the index to the column(s) being used.
int GOLD_HOARDED_COLUMN_INDEX = resultCursor.getColumnIndexOrThrow(
MyHoardContentProvider.KEY_GOLD_HOARDED_COLUMN);
int HOARD_NAME_COLUMN_INDEX = resultCursor.getColumnIndexOrThrow(
MyHoardContentProvider.KEY_GOLD_HOARD_NAME_COLUMN);
// Iterate over the cursors rows.
// The Cursor is initialized at before first, so we can
// check only if there is a “next” row available. If the
// result Cursor is empty, this will return false.
while (resultCursor.moveToNext()) {
float hoard = resultCursor.getFloat(GOLD_HOARDED_COLUMN_INDEX);
if (hoard > largestHoard) {
largestHoard = hoard;
hoardName = resultCursor.getString(HOARD_NAME_COLUMN_INDEX);
}
}
// Close the Cursor when you’ve finished with it.
resultCursor.close();

使用Cursor Loader进行异步查询

Cursor Loader存在于在每个Activity和Fragment中,可以实现异步查询和监听底层数据的变化。例如管理Cursor的生命周期,确保在Activity退出之前Cursor被关闭。

实现LoaderCallbacks接口

若要使用Cursor Loader,首先要实现LoaderManager.LoaderCallbacks接口:

LoaderManager.LoaderCallbacks<Cursor> loaderCallback = new LoaderManager.LoaderCallbacks<Cursor>()

LoaderCallback主要有这几个回调方法:

  • onCreateLoader
  • onLoadFinished
  • onLoaderReset
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
  // Construct the new query in the form of a Cursor Loader. Use the id
  // parameter to construct and return different loaders.
  String[] projection = null;
  String where = null;
  String[] whereArgs = null;
  String sortOrder = null;
  // Query URI
  Uri queryUri = MyContentProvider.CONTENT_URI;
  // Create the new Cursor loader.
  return new CursorLoader(DatabaseSkeletonActivity.this, queryUri,projection, where, whereArgs, sortOrder);
}
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
  // Replace the result Cursor displayed by the Cursor Adapter with the new result set.
  adapter.swapCursor(cursor);
  // This handler is not synchronized with the UI thread, so you will need to synchronize it before modifying any UI elements directly.
}
public void onLoaderReset(Loader<Cursor> loader) {
  // Remove the existing result Cursor from the List Adapter.
  adapter.swapCursor(null);
  // This handler is not synchronized with the UI thread, so you
  // will need to synchronize it before modifying any UI elements directly.
}

初始化和重启Cursor Loader

在Activity和Fragment中,可以调用getLoaderManager获得Cursor Loader

LoaderManager loaderManager = getLoaderManager();

获取Cursor Loader:

Bundle args = null;
loaderManager.initLoader(LOADER_ID, args, myLoaderCallbacks);

LOADER_ID用于标识获得的loader,args是可选参数,myLoaderCallbacks则是前面LoaderManager.LoaderCallbacks接口的实现。如果对应LOADER_ID的Cursor Loader不存在,那么系统会调用onCreateLoader方法来创建一个Loader。

使用Content Resolver增、改、删

插入数据:

// Create a new row of values to insert.
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put(MyHoardContentProvider.KEY_GOLD_HOARD_NAME_COLUMN, hoardName);
newValues.put(MyHoardContentProvider.KEY_GOLD_HOARDED_COLUMN, hoardValue);
newValues.put(MyHoardContentProvider.KEY_GOLD_HOARD_ACCESSIBLE_COLUMN, hoardAccessible);
// [ ... Repeat for each column / value pair ... ]
// Get the Content Resolver
ContentResolver cr = getContentResolver();
// Insert the row into your table
Uri myRowUri = cr.insert(MyHoardContentProvider.CONTENT_URI, newValues);

删除数据:

// Specify a where clause that determines which row(s) to delete.
// Specify where arguments as necessary.
String where = MyHoardContentProvider.KEY_GOLD_HOARDED_COLUMN + “=” + 0;
String whereArgs[] = null;
// Get the Content Resolver.
ContentResolver cr = getContentResolver();
// Delete the matching rows
int deletedRowCount = cr.delete(MyHoardContentProvider.CONTENT_URI, where, whereArgs);

修改数据:

// Create the updated row content, assigning values for each row.
ContentValues updatedValues = new ContentValues();
updatedValues.put(MyHoardContentProvider.KEY_GOLD_HOARDED_COLUMN, newHoardValue);
// [ ... Repeat for each column to update ... ]
// Create a URI addressing a specific row.
Uri rowURI = ContentUris.withAppendedId(MyHoardContentProvider.CONTENT_URI, hoardId);
// Specify a specific row so no selection clause is required.
String where = null;
String whereArgs[] = null;
// Get the Content Resolver.
ContentResolver cr = getContentResolver();
// Update the specified row.
int updatedRowCount = cr.update(rowURI, updatedValues, where, whereArgs);

使用Content Resolver读写Content Provider中的数据

public void addNewHoardWithImage(String hoardName, float hoardValue, boolean hoardAccessible, Bitmap bitmap) {
  // Create a new row of values to insert.
  ContentValues newValues = new ContentValues();
  // Assign values for each row.
  newValues.put(MyHoardContentProvider.KEY_GOLD_HOARD_NAME_COLUMN, hoardName);
  newValues.put(MyHoardContentProvider.KEY_GOLD_HOARDED_COLUMN, hoardValue);
  newValues.put(MyHoardContentProvider.KEY_GOLD_HOARD_ACCESSIBLE_COLUMN, hoardAccessible);
  // Get the Content Resolver
  ContentResolver cr = getContentResolver();
  // Insert the row into your table
  Uri myRowUri = cr.insert(MyHoardContentProvider.CONTENT_URI, newValues);
  try {
    // Open an output stream using the new row’s URI.
    OutputStream outStream = cr.openOutputStream(myRowUri);
    // Compress your bitmap and save it into your provider.
    bitmap.compress(Bitmap.CompressFormat.JPEG, 80, outStream);
  }catch (FileNotFoundException e) {
    Log.d(TAG, “No file found for this record.”);
  }
}
public Bitmap getHoardImage(long rowId) {
  Uri myRowUri = ContentUris.withAppendedId(MyHoardContentProvider.CONTENT_URI, rowId);
  try {
    // Open an input stream using the new row’s URI.
    InputStream inStream = getContentResolver().openInputStream(myRowUri);
    // Make a copy of the Bitmap.
    Bitmap bitmap = BitmapFactory.decodeStream(inStream);
    return bitmap;
  }catch (FileNotFoundException e) {
    Log.d(TAG, “No file found for this record.”);
  }
  return null;
}

Android 4 学习(17):使用Content Resolver的更多相关文章

  1. Android开发学习之路--Content Provider之初体验

    天气说变就变,马上又变冷了,还好空气不错,阳光也不错,早起上班的车上的人也不多,公司来的同事和昨天一样一样的,可能明天会多一些吧,那就再来学习android吧.学了两个android的组件,这里学习下 ...

  2. 我的Android 4 学习系列之数据库和Content Provider

    目录 创建数据库和使用SQLite 使用Content Provider.Cusor和Content Value来存储.共享和使用应用程序数据 使用Cursor Loader异步查询Content P ...

  3. Android 4 学习(16):Database and Content Providers

    参考<Professional Android 4 Development> Database and Content Providers Android Database简介 Andro ...

  4. Android Animation学习(二) ApiDemos解析:基本Animatiors使用

    Animator类提供了创建动画的基本结构,但是一般使用的是它的子类: ValueAnimator.ObjectAnimator.AnimatorSet ApiDemos中Animation部分是单独 ...

  5. Android:日常学习笔记(6)——探究活动(3)

    Android:日常学习笔记(6)——探究活动(3) 活动的生命周期 返回栈 Android中的活动是可以叠加的,我们每启动一个新活动,就会覆盖在原来的活动上,点击Back以后销毁最上面的活动,下面的 ...

  6. android 开发学习笔记 (一)

    每个app 都有一个自己的 linux 进程: 每个进程都在自己的虚拟机里执行 两个app 可以跑在一个进程,一个vm里 android app 四大组件:activity,content provi ...

  7. Android Animation学习(二) ApiDemos解析:基本Animators使用

    Android Animation学习(二) ApiDemos解析:基本Animatiors使用 Animator类提供了创建动画的基本结构,但是一般使用的是它的子类: ValueAnimator.O ...

  8. Android Testing学习01 介绍 测试测什么 测试的类型

    Android Testing学习01 介绍 测试测什么 测试的类型 Android 测试 测什么 1.Activity的生命周期事件 应该测试Activity的生命周期事件处理. 如果你的Activ ...

  9. Android开发学习之LauncherActivity开发启动的列表

    Android开发学习之LauncherActivity开发启动的列表 创建项目:OtherActivity 项目运行结果:   建立主Activity:OtherActivity.java [jav ...

随机推荐

  1. [IC]Lithograph(0)半导体制造的基本过程

    1. 晶圆片 Wafer 晶圆(Wafer)是指硅半导体集成电路制作所用的硅芯片,由于其形状为圆形,故称为晶圆.晶圆是生产集成电路所用的载体,一般意义晶圆多指单晶硅圆片. 半导体行业从图1到图2,是一 ...

  2. 【剑指offer】找出数组中任意一个重复的数字,C++实现

    原创博文,转载请注明出处! # 题目 # 思路 对于长度为n的数组,范围为0~n-1的数字而言,如果不粗在重复数字,则排序后数组元素和数组角标相同.如果存在重复数字,则在排序的过程中会出现不同下标对应 ...

  3. 为Linux服务器的SSH登录启用Google两步验证

    对于Linux服务器而言使用密钥登录要比使用密码登录安全的多,毕竟当前网上存在多个脚本到处进行爆破. 这类脚本都是通过扫描IP端的开放端口并使用常见的密码进行登录尝试,因此修改端口号也是非常有必要的. ...

  4. SaltStack简明教程

    第1章 SaltStack简明教程 1.1 SaltStack简介 SaltStack是基于Python开发的一套C/S架构配置管理工具(功能不仅仅是配置管理,如使用salt-cloud配置AWS E ...

  5. VS2013 tips

    1.创建一个connection时会自动产生一个localdb数据库文件,可以通过Server Explorer窗口查看这个localDB,注意,是Server Explorer窗口,而不是SQL S ...

  6. 像黑客一样!Chrome 完全键盘操作指南(原生快捷键 + Vimium 插件)

    有那么一波小伙伴,多数时候都不需要用到鼠标,通常他们正好是“黑客”.当你开始使用键盘操作一切时,便能体会到无需用鼠标瞄准按钮时的干脆,无需在键盘和鼠标之间移动手时的轻松. Chrome 原生自带大量快 ...

  7. Visual->UIElement->FrameworkElement,带来更多功能的同时也带来了更多的限制

    在 WPF 或 UWP 中,我们平时开发所遇到的那些 UI 控件或组件,都直接或间接继承自 Framework.例如:Grid.StackPanel.Canvas.Border.Image.Butto ...

  8. HAL层编写规范

    andriod HAL模块也有一个通用的入口地址,这个入口地址就是HAL_MODULE_INFO_SYM变量,通过它,我们可以访问到HAL模块中的所有想要外部访问到的方法.  在Linux系统中,后缀 ...

  9. gradle 构建包含源码配置

    参考配置: apply plugin: "idea" apply plugin: "groovy" apply plugin: "eclipse&qu ...

  10. demo 记录 通用方法什么的到这里抄一下

    function killerrors() { return true; } window.onerror = killerrors; //检查浏览器类型 function checkBrowser( ...