1、CursorLoader使用Demo
public class MainActivity extends Activity implements LoaderManager.LoaderCallbacks<Cursor> {
String TITLE = MediaStore.Audio.Media.TITLE;
String SINGER = MediaStore.Audio.Media.ARTIST;
String SONGURL = MediaStore.Audio.Media.DATA;
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
private LoaderManager loaderManager;
private Cursor myCursor;
private ListView lv;
private SimpleCursorAdapter adapter;
private String songUrl;
/**
* 创建loader之后, 会在子线程执行loadInBackground()方法进行加载数据
*/
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
CursorLoader loader = new CursorLoader(this, uri, null, null, null,null);
return loader;
}
/**
* loader加载数据完成,返回一个cursor对象,供我们查询数据
*/
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
myCursor = cursor;
Cursor oldCursor = adapter.swapCursor(cursor);
Log.e("tag", "onLoadFinished: " + oldCursor);
}
/**
* loader重置时回调,需要释放对这个loader数据有引用的cursor
*/
@Override
public void onLoaderReset(Loader<Cursor> loader) {
adapter.swapCursor(null);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intiData();
loaderManager = getLoaderManager();
//调用该方法后会回调onCreateLoader来创建loader对象
loaderManager.initLoader(1, null, this);
}
private void intiData() {
lv = (ListView) findViewById(R.id.lv);
adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, null,
new String[] {TITLE, SINGER }, new int[] { android.R.id.text1, android.R.id.text2 },
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
myCursor.moveToPosition(position);
songUrl = myCursor.getString(myCursor.getColumnIndex(SONGURL));
Log.e("tag", "clickStart: " + songUrl);
}
});
}
public void clickStart(View view) {
Intent i = new Intent(MainActivity.this, MusicService.class);
i.setAction("pause");
// i.putExtra("id", songUrl);
startService(i);
Log.e("tag", "clickStart: ");
// Log.e("tag", "clickStart: " );
}
public void clickStop(View view) {
Intent i = new Intent(MainActivity.this, MusicService.class);
i.setAction("stop");
startService(i);
}
}
2、AsyncTaskLoader详细使用DEMO
基于上篇的Fragments 代码,添加Loaders功能,实现加载应用程序数据到界面上,DEMO的运行效果如下:
核心代码为
应用程序的数据对象类:
public static class AppEntry {
private final AppListLoader mLoader;
private final ApplicationInfo mInfo;
private final File mApkFile;
private String mLable;
private Drawable mIcon;
private boolean mMounted; public AppEntry(AppListLoader loader, ApplicationInfo info) {
mLoader = loader;
mInfo = info;
mApkFile = new File(info.sourceDir);
} public ApplicationInfo getApplicationInfo() {
return mInfo;
} public String getLable() {
return mLable;
} public Drawable getIcon() {
if (mIcon == null) {
if (mApkFile.exists()) {
mIcon = mInfo.loadIcon(mLoader.mPm);
return mIcon;
} else {
mMounted = false;
}
} else if (!mMounted) {
if (mApkFile.exists()) {
mMounted = true;
mIcon = mInfo.loadIcon(mLoader.mPm);
return mIcon;
}
} else {
return mIcon;
}
return mLoader.getContext().getResources().getDrawable(
android.R.drawable.sym_def_app_icon);
} @Override
public String toString() {
// TODO Auto-generated method stub
return mLable.toString();
} void loadLable(Context mContext) {
if (mLable == null || !mMounted) {
if (!mApkFile.exists()) {
mMounted = false;
mLable = mInfo.packageName;
} else {
mMounted = true;
CharSequence lable = mInfo.loadLabel(mContext
.getPackageManager());
mLable = lable != null ? lable.toString()
: mInfo.packageName;
}
}
}
}
实现AsyncTaskLoader 加载数据
public static class AppListLoader extends AsyncTaskLoader<List<AppEntry>> { final InterestingConfigChanges mLastConfig = new InterestingConfigChanges();
final PackageManager mPm; List<AppEntry> mApps;
packageIntentReceiver mPackageObserver; public AppListLoader(Context context) {
super(context);
// TODO Auto-generated constructor stub
mPm = getContext().getPackageManager();
} @Override
public List<AppEntry> loadInBackground() {
// TODO Auto-generated method stub
List<ApplicationInfo> apps = mPm
.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES
| PackageManager.GET_DISABLED_COMPONENTS);
if (apps == null)
apps = new ArrayList<ApplicationInfo>();
final Context mContext = getContext();
List<AppEntry> entries = new ArrayList<AppEntry>(apps.size());
for (ApplicationInfo info : apps) {
AppEntry entry = new AppEntry(this, info);
entry.loadLable(mContext);
entries.add(entry);
}
Collections.sort(entries, ALPHA_COMPARATOR);
return entries;
} @Override
public void deliverResult(
List<com.xuzhi.fragment.FragmentDemoActivity.AppEntry> data) {
// TODO Auto-generated method stub
if (isReset()) {
if (data != null) {
//释放资源处理
}
}
List<AppEntry> oladApps=data;
mApps=data;
if(isStarted()){
super.deliverResult(data);
}
if(oladApps!=null){
//释放资源
}
}
protected void onStartLoading() {
if(mApps!=null)
deliverResult(mApps);
if(mPackageObserver==null)
mPackageObserver=new packageIntentReceiver(this);
boolean configChange=mLastConfig.applyNewConfig(getContext().getResources());
if(takeContentChanged()|| mApps== null || configChange){
forceLoad();
}
};
@Override
public void onCanceled(
List<com.xuzhi.fragment.FragmentDemoActivity.AppEntry> data) {
// TODO Auto-generated method stub
super.onCanceled(data);
cancelLoad();
}
@Override
protected void onReset() {
// TODO Auto-generated method stub
super.onReset();
onStopLoading();
if(mApps!=null){
//释放资源
mApps=null;
}
if(mPackageObserver!=null){
getContext().unregisterReceiver(mPackageObserver);
mPackageObserver=null;
}
}
}
实现数据源:
public static class AppListAdapter extends ArrayAdapter<AppEntry>{
private LayoutInflater mInflater;
public AppListAdapter(Context context) {
// TODO Auto-generated constructor stub
super(context, android.R.layout.simple_list_item_2);
mInflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void setData(List<AppEntry> data){
clear();
if(data!=null){
addAll(data);
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View view;
if(convertView==null){
view=mInflater.inflate(R.layout.list_item_icon_text, parent,false);
}else{
view=convertView;
}
AppEntry item=getItem(position);
((ImageView)view.findViewById(R.id.icon)).setImageDrawable(item.getIcon());
((TextView)view.findViewById(R.id.text)).setText(item.getLable());
return view;
}
}
在Activity 或者Fragments 里面实现接口:
public static class DetailsFragment extends ListFragment implements OnQueryTextListener,LoaderCallbacks<List<AppEntry>>
实现接口里面的函数:
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
return false;
} public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
return false;
}
public Loader<List<com.xuzhi.fragment.FragmentDemoActivity.AppEntry>> onCreateLoader(
int id, Bundle args) {
// TODO Auto-generated method stub
return new AppListLoader(getActivity());
} /**
* Load 完成后
*/
public void onLoadFinished(
Loader<List<com.xuzhi.fragment.FragmentDemoActivity.AppEntry>> arg0,
List<com.xuzhi.fragment.FragmentDemoActivity.AppEntry> arg1) {
// TODO Auto-generated method stub
mAdapter.setData(arg1);
if (isResumed()) {
setListShown(true);
} else {
setListShownNoAnimation(true);
}
} /**
* Loader 重置时
*/
public void onLoaderReset(
Loader<List<com.xuzhi.fragment.FragmentDemoActivity.AppEntry>> arg0) {
// TODO Auto-generated method stub
mAdapter.setData(null);
}
得到LoaderManager初始化Loader,启动加载在Fragment 的onActivityCreated回调方法上添加,本DEMO的DetailsFragment类添加:
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
mAdapter = new AppListAdapter(getActivity());
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.
getLoaderManager().initLoader(0, null, this);
}
参考资料:
Android Loaders(三)实现一个Base Loader
Android Loader使用详解的更多相关文章
-
android:ToolBar详解
android:ToolBar详解(手把手教程) 泡在网上的日子 发表于 2014-11-18 12:49 第 124857 次阅读 ToolBar 42 来源 http://blog.mosil.b ...
-
Android之canvas详解
首先说一下canvas类: Class Overview The Canvas class holds the "draw" calls. To draw something, y ...
-
【转】Android Canvas绘图详解(图文)
转自:http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2012/1212/703.html Android Canvas绘图详解(图文) 泡 ...
-
Android 核心分析 之八Android 启动过程详解
Android 启动过程详解 Android从Linux系统启动有4个步骤: (1) init进程启动 (2) Native服务启动 (3) System Server,Android服务启动 (4) ...
-
Android GLSurfaceView用法详解(二)
输入如何处理 若是开发一个交互型的应用(如游戏),通常需要子类化 GLSurfaceView,由此可以获取输入事件.下面有个例子: java代码: package eoe.ClearTes ...
-
Android编译过程详解(一)
Android编译过程详解(一) 注:本文转载自Android编译过程详解(一):http://www.cnblogs.com/mr-raptor/archive/2012/06/07/2540359 ...
-
android屏幕适配详解
android屏幕适配详解 官方地址:http://developer.android.com/guide/practices/screens_support.html 一.关于布局适配建议 1.不要 ...
-
Android.mk文件详解(转)
源:Android.mk文件详解 从对Makefile一无所知开始,折腾了一个多星期,终于对Android.mk有了一个全面些的了解.了解了标准的Makefile后,发现Android.mk其实是把真 ...
-
Android Studio 插件开发详解四:填坑
转载请标明出处:http://blog.csdn.net/zhaoyanjun6/article/details/78265540 本文出自[赵彦军的博客] 在前面我介绍了插件开发的基本流程 [And ...
随机推荐
-
HBase工程师线上工作经验总结----HBase常见问题及分析
阅读本文可以带着下面问题:1.HBase遇到问题,可以从几方面解决问题?2.HBase个别请求为什么很慢?你认为是什么原因?3.客户端读写请求为什么大量出错?该从哪方面来分析?4.大量服务端excep ...
-
TYVJ P1093 验证数独 Label:none
背景 XX学校风靡一款智力游戏,也就是数独(九宫格),先给你一个数独,并需要你验证是否符合规则. 描述 具体规则如下:每一行都用到1,2,3,4,5,6,7,8,9,位置不限,每一列都用到1,2,3, ...
-
js文字从左边飞入效果
贴代码之前,我们先讲一下它的原理,我们使用setInterval,让文字一开始置于屏幕看不到的位置,左右上下都可以,然后让它的位置不断移入到屏幕看得到的位置. 下面上代码: html: <h2 ...
-
npm常用功能
1. npm -v在命令行中输入该代码,可以查看npm当前版本号 2.安装依赖包2.1 npm install <name>先使用cd命令跳转到需要安装模块的目录,在该目录下执行np ...
-
Chrome浏览器录屏扩展插件
Chrome浏览器录屏扩展插件,可以录制网页操作或者桌面操作.生成MP4 Loom https://chrome.google.com/webstore/detail/loom-video-recor ...
-
[转]TensorFlow---岂止深度学习
原文链接 TensorFlow不仅可以用于深度学习自动求导,它也可用于构建传统机器学习和经典算法. TensorFlow提供了"一揽子"常用数值计算和机器学习算法的构建模块.在本文 ...
- 【eclipse】删除工作空间
-
爬虫之Xpath案例
案例:使用XPath的爬虫 现在我们用XPath来做一个简单的爬虫,我们尝试爬取某个贴吧里的所有帖子,并且将该这个帖子里每个楼层发布的图片下载到本地. # tieba_xpath.py #!/usr/ ...
-
HDU 2191 【多重背包】
Input 输入数据首先包含一个正整数C,表示有C组测试用例,每组测试用例的第一行是两个整数n和m(1<=n<=100, 1<=m<=100),分别表示经费的金额和大米的种类, ...
-
Nuget~管理自己的包包
很久很久以前,自己就想有个包包,最近又从网上淘了一个,价格不便宜呢,99块,还是个小腰包,不过作工还算精良,我喜欢的类型,帆布休闲包,可以将我的手机,耳机,水,小烟,小酒,小伞都放里,方便至极,哈哈!