android在异步任务中关闭Cursor的代码方法
时间:2022-04-21 18:07:32
查询数据会比较耗时,所以我们想把查询数据放在一个异步任务中,查询结果获得Cursor,然后在onPostExecute (Cursor result)方法中设置Adapter,我们可能会想到使用Activity的managedQuery来生成Cursor,这样Cursor就会与Acitivity的生命周期一致了,多么完美的解决方法!然而事实上managedQuery也有很大的局限性,managedQuery生成的Cursor必须确保不会被替换,因为可能很多程序事实上查询条件都是不确定的,因此我们经常会用新查询的Cursor来替换掉原先的Cursor。因此这种方法适用范围也是很小。
我们不能直接将Cursor关闭掉,但是注意,CursorAdapter在Acivity结束时并没有自动的将Cursor关闭掉,因此,你需要在onDestroy函数中,手动关闭。
@Override
protected void onDestroy() {
super.onDestroy();
mPhotoLoader.stop();
if(mAdapter != null && mAdapter.getCursor() != null) {
mAdapter.getCursor().close();
}
}
如果没有在Adapter中用到Cursor,可以手动关闭Cursor。
Cursor cursor = null;
try{
cursor = mContext.getContentResolver().query(uri,null,null,null,null);
if(cursor != null){
cursor.moveToFirst();
//do something
}
}catch(Exception e){
e.printStatckTrace();
}finally{
if(cursor != null){
cursor.close();
}
}
标签:android,异步任务,Cursor
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
浅谈java+内存分配及变量存储位置的区别
2022-07-09 00:46:47
JavaFX实现UI美观效果代码实例
2021-08-27 21:02:15
![](https://img.aspxhome.com/file/2023/6/62206_0s.jpg)
c# 使用handle.exe解决程序更新文件被占用的问题
2023-09-02 04:27:59
Mybatis的特点及优点
2022-11-19 16:27:54
java算法题解牛客BM99顺时针旋转矩阵示例
2021-07-08 18:55:18
![](https://img.aspxhome.com/file/2023/3/80953_0s.jpg)
Spring boot Mybatis 整合(完整版)
2023-03-28 17:14:32
![](https://img.aspxhome.com/file/2023/3/87143_0s.png)
SpringBoot如何使用RateLimiter通过AOP方式进行限流
2023-09-16 18:18:44
![](https://img.aspxhome.com/file/2023/3/58583_0s.png)
Android开发使用Databinding实现关注功能mvvp
2023-07-23 19:27:32
![](https://img.aspxhome.com/file/2023/2/102592_0s.jpg)
Java如何在PDF中添加ToolTip工具提示
2021-12-31 12:12:53
![](https://img.aspxhome.com/file/2023/6/77456_0s.png)
C#警惕匿名方法造成的变量共享实例分析
2021-08-26 19:35:22
Java经典面试题最全汇总208道(四)
2023-11-08 23:59:26
![](https://img.aspxhome.com/file/2023/5/59065_0s.png)
C#实现为一张大尺寸图片创建缩略图的方法
2021-08-03 21:07:15
Java C++ 算法题解leetcode669修剪二叉搜索树示例
2022-09-22 04:56:13
![](https://img.aspxhome.com/file/2023/9/61119_0s.png)
Java Socket实现单线程通信的方法示例
2022-04-22 15:43:02
Flutter实现手势识别功能详解方法
2022-12-21 15:41:41
![](https://img.aspxhome.com/file/2023/5/116025_0s.gif)
结合.net框架在C#派生类中触发基类事件及实现接口事件
2022-02-23 20:39:57
Android布局之绝对布局AbsoluteLayout详解
2023-07-26 07:44:27
![](https://img.aspxhome.com/file/2023/8/83518_0s.png)
Android Jetpack库剖析之LiveData组件篇
2022-08-31 02:08:13
Android 实现闪屏页和右上角的倒计时跳转实例代码
2022-12-10 17:32:32
![](https://img.aspxhome.com/file/2023/6/123356_0s.png)
C#控制台程序如何发布到服务器Linux上运行
2022-07-17 05:57:52
![](https://img.aspxhome.com/file/2023/3/129763_0s.png)