Cursor的关闭问题


    最近在工作中处理了一些内存泄露的问题,在这个过程中我尤其发现了一些基本的问题反而忽略导致内存泄露,比如静态变量,cursor关闭,流关闭,线程,定时器,反注册,bitmap等等,我稍微统计并总结了一下,当然了,这些问题这么说起来比较笼统,接下来我会根据问题,把一些实例代码贴出来,一步一步分析,在具体的场景下,用行之有效的方法,找出泄露的根本原因,并给出解决方案。
    现在,就从cursor关闭的问题开始把,谁都知道cursor要关闭,但是往往相反,人们却常常忘记关闭,因为真正的应用场景可能并非理想化的简单。
1. 理想化的cursor关闭

// Sample Code
Cursor cursor = db.query();
List<String> list = convertToList(cursor);
cursor.close();

    这是最简单的cursor使用场景,如果这里的cursor没有关闭,我想可能会引起万千口水,一片骂声。
    但是实际场景可能并非如此,这里的cursor可能不会关闭,至少有以下两种可能。

2. Cursor未关闭的可能
     (1). cursor.close()之前发生异常。
     (2). cursor需要继续使用,不能马上关闭,后面忘记关闭了。

3. Cursor.close()之前发生异常
     这个很容易理解,应该也是初学者最开始碰到的常见问题,举例如下:

try { 
    Cursor c = queryCursor(); 
    int a = c.getInt(1); 
    ......
    // 如果出错,后面的cursor.close()将不会执行
    ......
    c.close(); 
} catch (Exception e) { 
} 
如果出错,后面的cursor.close()将不会执行

  正确写法应该是:

Cursor c;
try { 
    c = queryCursor(); 
    int a = c.getInt(1); 
    ......
    // 如果出错,后面的cursor.close()将不会执行
    //c.close(); 
} catch (Exception e) { 
} finally{
    if (c != null) {
        c.close();
    }
} 

    很简单,但是需要时刻谨记。

4. Cursor需要继续使用,不能马上关闭
    有没有这种情况?怎么办?
    答案是有,CursorAdapter就是一个典型的例子。
    CursorAdapter示例如下:

mCursor = getContentResolver().query(CONTENT_URI, PROJECTION,
null, null, null);
mAdapter = new MyCursorAdapter(this, R.layout.list_item, mCursor);
setListAdapter(mAdapter);
// 这里就不能关闭执行mCursor.close(),
// 否则list中将会无数据

5. 这样的Cursor应该什么时候关闭呢?

    这是个可以说好回答也可以说不好回答的问题,那就是在Cursor不再使用的时候关闭掉。

    比如说,

    上面的查询,如果每次进入或者resume的时候会重新查询执行。

    一般来说,也只是这种需求,很少需要看不到界面的时候还在不停地显示查询结果,如果真的有,不予讨论,记得最终关掉就OK了。

    这个时候,我们一般可以在onStop()方法里面把cursor关掉(同时意味着你可能需要在onResume()或者onStart()重新查询一下)。

@Override
protected void onStop() {
    super.onStop();
    // mCursorAdapter会释放之前的cursor,相当于关闭了cursor
    mCursorAdapter.changeCursor(null);
}

  我专门附上CursorAdapter的changeCursor()方法源码,让大家看的更清楚,免得不放心changeCursor(null)方法:

/**
 * Change the underlying cursor to a new cursor. If there is an existing cursor it will be
 * closed.
 *
 * @param cursor The new cursor to be used
 */
public void changeCursor(Cursor cursor) {
    Cursor old = swapCursor(cursor);
    if (old != null) {
        old.close();
    }
}
 
/**
 * Swap in a new Cursor, returning the old Cursor.  Unlike
 * {@link #changeCursor(Cursor)}, the returned old Cursor is <em>not</em>
 * closed.
 *
 * @param newCursor The new cursor to be used.
 * @return Returns the previously set Cursor, or null if there wasa not one.
 * If the given new Cursor is the same instance is the previously set
 * Cursor, null is also returned.
 */
public Cursor swapCursor(Cursor newCursor) {
    if (newCursor == mCursor) {
        return null;
    }
    Cursor oldCursor = mCursor;
    if (oldCursor != null) {
        if (mChangeObserver != null) oldCursor.unregisterContentObserver(mChangeObserver);
        if (mDataSetObserver != null) oldCursor.unregisterDataSetObserver(mDataSetObserver);
    }
    mCursor = newCursor;
    if (newCursor != null) {
        if (mChangeObserver != null) newCursor.registerContentObserver(mChangeObserver);
        if (mDataSetObserver != null) newCursor.registerDataSetObserver(mDataSetObserver);
        mRowIDColumn = newCursor.getColumnIndexOrThrow("_id");
        mDataValid = true;
        // notify the observers about the new cursor
        notifyDataSetChanged();
    } else {
        mRowIDColumn = -1;
        mDataValid = false;
        // notify the observers about the lack of a data set
        notifyDataSetInvalidated();
    }
    return oldCursor;
}

6. 实战AsyncQueryHandler中Cursor的关闭问题
    AsyncQueryHandler是一个很经典很典型的分析Cursor的例子,不仅一阵见血,能举一反三,而且非常常见,为以后避免。
    AsyncQueryHandler文档参考地址:
    http://developer.android.com/reference/android/content/AsyncQueryHandler.html
    下面这段代码是Android2.3系统中Mms信息主页面ConversationList源码的一部分,大家看看Cursor正确关闭了吗?

转载自:https://blog.csdn.net/love_xiaozhao/article/details/52243308

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值