android中CursorLoader类使用

2024-05-07 11:58
文章标签 android 使用 cursorloader

本文主要是介绍android中CursorLoader类使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

工作内容集中到Contact模块,这个应用查询数据的地方很多,其使用了CursorLoader这个工具大大简化了代码复杂度。android自3.0提供了Loader机制,当时google的API只是简单的介绍了一下没有给出用法,大家很少有关注。后来因为重度模型下的性能优化,R&D的朋友发现这个东西非常给力,这才开始注意到这个强大的工具。CursorLoader是Loader的子类,可以说是Loader的升级版。这篇小结以loader为基础说明,弄懂原理之后也就明白了CursorLoader。
先说说google官方对Loader的介绍Loader对activity和fragment可用;Loader可以移步加载数据;loader自己会监视数据源的变化并且会主动上报;当发生配置上的变化,重新生成的loader会自动连接到变化前的cursor,这样就避免再查一次数据库。咱自己在补充一个,loader能在应用不使用查询到的资源时候,自动将其释放。这些介绍自android3.0之后,就可以从官方文档山看到。当时依据这些并不知道怎么样使用,看了framework侧的实现之后还是一头雾水:咋用。现在来看这就像activity一样,我们可以不知道framework中怎么样开始一个activity怎么样管理activity但是我们仍然能很好的使用activity;对于CursorLoader,我们大可以不必知道framework中的原理,只要利用好google提供的接口LoaderManager以及为其注册事件的接口LoaderManager.LoaderCallbacks就可以实现我们需要的功能。
实际上CursorLoader完全可以看成一个很牛的查询工具,拥有一般的查询不具备的能力,如上面的google官方介绍。我们通过LoaderManager.LoaderCallbacks接口来在适当的时候提供查询配置或者利用查询返回到的结果。使用好CursorLoader重在实现好LoaderManager.LoaderCallbacks接口。看下这个接口里面提供了哪些方法:
代码如下:

public interface LoaderCallbacks<D> { public Loader<D> onCreateLoader(int id, Bundle args); public void onLoadFinished(Loader<D> loader, D data); public void onLoaderReset(Loader<D> loader); 
}

第一个方法onCreateLoader是创建Loader时候调用,是为了提供查询的配置,比如查询地址,查询项目等。这个方法会在loader初始化也就是注册这个接口的时候调用,常见代码如下:
getLoaderManager().initLoader(0, null, this);
getLoaderManager().initLoader(0, null, this);
第一个参数是当前activity里面loader的ID,一般为0
第二个参数一般置null
第三个就是实现了LoaderManager.LoaderCallbacks的类,一般就是当前activity。
这句代码执行之后就会执行onCreateLoader,然后去查询,查询结束之后就会执行onLoadFinished,做你需要做的事情。一般就在第二个方法里面利用查询结果,如传递到一个adapter进行显示。第三个方法onLoaderReset是在我们的配置发生变化的,使用restartLoader(int , Bundle ,LoaderManager.LoaderCallbacks)方法重新初始化loader之后调用的,一般是用来释放对前面loader查询到的结果引用。对Loader的使用只需要在重新初始化之前去除引用,退出activity时候不需要关闭cursor释放资源。
到这里loader的用法就已经说完了,记住上面三个方法的用处,在适当的地方初始化loader,我们就可以利用Loader实现我们的需要。现在说说Loader和CursorLoader的关系:Loader是核心,其已经实现了基本功能;AsyncTaskLoader继承自Loader,主要任务就是将耗时操作从主线程中剥离出来;CursorLoader继承自AsyncTaskLoader,是泛型类的一个具体类,也是我们最常用Loader。
Loader的到来给android应用开发带来了很大的方便。在数据加载的性能优化中有一项分布加载,没有Loader之前,我们需要将查询实现在AsyncQueryHandler类里面,在其onQueryComplete回调方法里面触发后续查询。上面这些需要自定义一个内部类,一堆代码,搞得晕乎乎的。%>_<% 用来Loader只要在onLoadFinished里面增加一些判断即可,很方便

示例代码如下:

/** * A {@link ListFragment} that shows the use of a {@link LoaderManager} to * display a list of contacts accessed through a {@link Cursor}. */  
/* * (1)继承Fragment或者其子类,用于创建一个Fragment。实现LoaderManager.LoaderCallbacks接口,用于与Loader的交互 * 。 官方文档: A callback interface for a client to interact with the LoaderManager. * For example, you use the onCreateLoader() callback method to create a new * loader. */  
public class CursorLoaderListFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> {  // This is the Adapter being used to display the list's data.  SimpleCursorAdapter mAdapter;  // The SearchView for doing filtering.  SearchView mSearchView;  /* * (2)在Activity被创建时调用此方法。Called when the fragment's activity has been * created and this fragment's view hierarchy instantiated. You typically * initialize a Loader within the activity's onCreate() method, or within * the fragment's onActivityCreated() method. */@Override  public void onActivityCreated(Bundle savedInstanceState) {  super.onActivityCreated(savedInstanceState);  // Give some text to display if there is no data. In a real  // application this would come from a resource.  setEmptyText("No phone numbers");  /* * Create an empty adapter we will use to display the loaded data. The * simple_list_item_2 layout contains two rows on top of each other * (text1 and text2) that will show the contact's name and status. */  // (3)设置Fragment的顯示內容  mAdapter = new SimpleCursorAdapter(getActivity(),  android.R.layout.simple_list_item_2, null, new String[] {  Contacts.DISPLAY_NAME, Contacts.CONTACT_STATUS },  new int[] { android.R.id.text1, android.R.id.text2 }, 0);  setListAdapter(mAdapter);  // Start out with a progress indicator.  setListShown(false);  // Prepare the loader. Either re-connect with an existing one,  // or start a new one.  /* * (4)創建一個Loader,此Loader用于為Fragment載入內容。You typically initialize a * Loader within the activity's onCreate() method, or within the * fragment's onActivityCreated() method. * 此方法將自動調用LoaderManager.LoaderCallbacks接口的onCreateLoader方法。 */  getLoaderManager().initLoader(0, null, this);  }  /** * An item has been clicked in the {@link ListView}. Display a toast with * the tapped item's id. */  @Override  public void onListItemClick(ListView l, View v, int position, long id) {  Toast.makeText(getActivity(), "Item clicked: " + id, Toast.LENGTH_LONG)  .show();  }  // These are the Contacts rows that we will retrieve.  static final String[] CONTACTS_SUMMARY_PROJECTION = new String[] {  Contacts._ID, Contacts.DISPLAY_NAME, Contacts.CONTACT_STATUS,  Contacts.LOOKUP_KEY, };  /* * (5)Loader被創建時的操作,一般用于加載內容。In this example, the onCreateLoader() callback * method creates a CursorLoader. You must build the CursorLoader using its * constructor method, which requires the complete set of information needed * to perform a query to the ContentProvider. */public Loader<Cursor> onCreateLoader(int id, Bundle args) {  // This is called when a new Loader needs to be created. This  // sample only has one Loader, so we don't care about the ID.  // First, pick the base URI to use depending on whether we are  // currently filtering.  Uri baseUri;  baseUri = Contacts.CONTENT_URI;  // Now create and return a CursorLoader that will take care of  // creating a Cursor for the data being displayed.  String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("  + Contacts.HAS_PHONE_NUMBER + "=1) AND ("  + Contacts.DISPLAY_NAME + " != '' ))";  String order = Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";  return new CursorLoader(getActivity(), baseUri,  CONTACTS_SUMMARY_PROJECTION, select, null, order);  }  /* * (6)内容被加载完成后的操作。The loader will release the data once it knows the * application is no longer using it. For example, if the data is a cursor * from a CursorLoader, you should not call close() on it yourself. If the * cursor is being placed in a CursorAdapter, you should use the * swapCursor() method so that the old Cursor is not closed. */public void onLoadFinished(Loader<Cursor> loader, Cursor data) {  // Swap the new cursor in. (The framework will take care of closing the  // old cursor once we return.)  // Swap in a new Cursor, returning the old Cursor. Unlike  // changeCursor(Cursor), the returned old Cursor is not closed.  mAdapter.swapCursor(data);  // The list should now be shown.  if (isResumed()) {  setListShown(true);  } else {  setListShownNoAnimation(true);  }  }  // (7)Loader被重新加载时的操作。  public void onLoaderReset(Loader<Cursor> loader) {  // This is called when the last Cursor provided to onLoadFinished()  // above is about to be closed. We need to make sure we are no  // longer using it.  mAdapter.swapCursor(null);  }  }  

本文为两个文章整理得到,原文地址如下:
http://www.jb51.net/article/37767.htm
http://blog.csdn.net/jediael_lu/article/details/16354815
http://blog.csdn.net/jediael_lu/article/details/16354783

这篇关于android中CursorLoader类使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/967292

相关文章

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注

Python内置函数之classmethod函数使用详解

《Python内置函数之classmethod函数使用详解》:本文主要介绍Python内置函数之classmethod函数使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 类方法定义与基本语法2. 类方法 vs 实例方法 vs 静态方法3. 核心特性与用法(1编程客

Linux中压缩、网络传输与系统监控工具的使用完整指南

《Linux中压缩、网络传输与系统监控工具的使用完整指南》在Linux系统管理中,压缩与传输工具是数据备份和远程协作的桥梁,而系统监控工具则是保障服务器稳定运行的眼睛,下面小编就来和大家详细介绍一下它... 目录引言一、压缩与解压:数据存储与传输的优化核心1. zip/unzip:通用压缩格式的便捷操作2.

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

Go语言数据库编程GORM 的基本使用详解

《Go语言数据库编程GORM的基本使用详解》GORM是Go语言流行的ORM框架,封装database/sql,支持自动迁移、关联、事务等,提供CRUD、条件查询、钩子函数、日志等功能,简化数据库操作... 目录一、安装与初始化1. 安装 GORM 及数据库驱动2. 建立数据库连接二、定义模型结构体三、自动迁

ModelMapper基本使用和常见场景示例详解

《ModelMapper基本使用和常见场景示例详解》ModelMapper是Java对象映射库,支持自动映射、自定义规则、集合转换及高级配置(如匹配策略、转换器),可集成SpringBoot,减少样板... 目录1. 添加依赖2. 基本用法示例:简单对象映射3. 自定义映射规则4. 集合映射5. 高级配置匹

Spring 框架之Springfox使用详解

《Spring框架之Springfox使用详解》Springfox是Spring框架的API文档工具,集成Swagger规范,自动生成文档并支持多语言/版本,模块化设计便于扩展,但存在版本兼容性、性... 目录核心功能工作原理模块化设计使用示例注意事项优缺点优点缺点总结适用场景建议总结Springfox 是

嵌入式数据库SQLite 3配置使用讲解

《嵌入式数据库SQLite3配置使用讲解》本文强调嵌入式项目中SQLite3数据库的重要性,因其零配置、轻量级、跨平台及事务处理特性,可保障数据溯源与责任明确,详细讲解安装配置、基础语法及SQLit... 目录0、惨痛教训1、SQLite3环境配置(1)、下载安装SQLite库(2)、解压下载的文件(3)、

使用Python绘制3D堆叠条形图全解析

《使用Python绘制3D堆叠条形图全解析》在数据可视化的工具箱里,3D图表总能带来眼前一亮的效果,本文就来和大家聊聊如何使用Python实现绘制3D堆叠条形图,感兴趣的小伙伴可以了解下... 目录为什么选择 3D 堆叠条形图代码实现:从数据到 3D 世界的搭建核心代码逐行解析细节优化应用场景:3D 堆叠图