当前位置: 移动技术网 > IT编程>移动开发>Android > android在异步任务中关闭Cursor的代码方法

android在异步任务中关闭Cursor的代码方法

2019年07月24日  | 移动技术网IT编程  | 我要评论

鳐鳌虾,森林猢狲军需官,宅乐购卡盟

查询数据会比较耗时,所以我们想把查询数据放在一个异步任务中,查询结果获得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();
    }
}

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网