我应该关闭本地数据库游标吗?

时间:2012-03-08 21:56:17

标签: java android sqlite

我的代码如下所示:

public static synchronized String getPreferenceString(Context context, String key)
    {
        Cursor c = DatabaseHelper.getDatabase(context).query(TABLE_NAME, new String[]{ "Value" }, "Key=?", new String[]{ key }, null, null, null, null);

        if (c.getCount() == 0)
        {
            c.close();
            return "";
        }

        c.moveToFirst();
        String retVal = c.getString(0);
        c.close();

        return retVal;
    }

基本上,我从数据库表中获取特定值。它工作得很好,但我想美化我的代码所以它可能看起来像这样:

public static synchronized String getPreferenceString(Context context, String key)
    {
        Cursor c = DatabaseHelper.getDatabase(context).query(TABLE_NAME, new String[]{ "Value" }, "Key=?", new String[]{ key }, null, null, null, null);

        if (c.getCount() == 0) return "";

        c.moveToFirst();
        return c.getString(0);
    }

可以,或者我应该关闭这些游标吗?

1 个答案:

答案 0 :(得分:7)

    public static synchronized String getPreferenceString(Context context, String key)
    {
        Cursor c = DatabaseHelper.getDatabase(context).query(TABLE_NAME, new String[] { "Value" }, "Key=?",
                new String[] { key }, null, null, null, null);

        if (c == null)
             return "";

        try {    
            return c.moveToFirst() ? c.getString(0) : "";
        } finally {
            c.close();
        }
    }

你应该始终关闭你的光标,除非它被应用程序以某种方式管理(Android自动装载加载器等等)。