Android:我需要关闭 Cursor 对象吗? [英] Android: do I need to close Cursor objects?

查看:24
本文介绍了Android:我需要关闭 Cursor 对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的数据库适配器类中,我有很多这样的方法:

In my database adapter class, I have many methods like this:

public long getContactId(final String phoneNumber) throws SQLException {
    final Cursor cur = mDb.rawQuery(
            "select contact_id from contactphones where number=? limit 1;",
            new String[] { phoneNumber });
    return cur.moveToFirst() ? cur.getLong(0) : -1;
}

我很欣赏这种方法的简洁性.但我不是在调用 Cursor.close(),我不确定这是否有问题.Cursor 是否会在 Cursor.finalize() 中关闭并释放其资源?否则我将不得不这样做:

I appreciate the brevity of a method like that. But I am not calling Cursor.close(), and I'm not sure if that is a problem or not. Would the Cursor be closed and its resources freed in the Cursor.finalize()? Otherwise I would have to do:

public long getContactId(final String phoneNumber) throws SQLException {
    final Cursor cur = mDb.rawQuery(
            "select contact_id from contactphones where number=? limit 1;",
            new String[] { phoneNumber });
    final boolean retVal = cur.moveToFirst() ? cur.getLong(0) : -1;
    cur.close();
    return retVal;
}

推荐答案

是的,建议在使用完该游标对象后关闭游标,以便游标在关闭时可以做它想做的任何内务工作.

Yes, it's recommended to close the cursor when you are done using that cursor object so that cursor can do whatever house keeping work it wants to do upon closure.

这篇关于Android:我需要关闭 Cursor 对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆