• android在异步任务中如何关闭Cursor


      在我们开发应用的时候,很多时候会遇到这种问题。

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

      

     1 Cursor cursor = null;
     2 try{
     3     cursor = mContext.getContentResolver().query(uri,null,null,null,null);
     4     if(cursor != null){
     5         cursor.moveToFirst();
     6     //do something
     7     }
     8 }catch(Exception e){
     9     e.printStatckTrace();
    10 }finally{
    11     if(cursor != null){
    12         cursor.close();
    13     }
    14 }
  • 相关阅读:
    xposed的基本使用
    scrapy发送邮件
    Image Pipeline
    javax.validation.ConstraintViolationException---Hibernate后台实体校验
    oracle中lead和lag函数 (转载)
    oracle中根据当前记录查询前一条和后一条记录
    物化视图知识了解(转载)
    10个线程同步处理1000行消息
    SQL语句执行效率及分析(note)
    js对文本框特殊字符串过滤
  • 原文地址:https://www.cnblogs.com/shang53880/p/2507943.html
Copyright © 2020-2023  润新知