My code looks like this:
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;
}
Basically, I’m getting specific value out of database table. It works great but I want to prettify my code so it maybe looks like this:
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);
}
Is it ok or I should close those cursors?
You should always close your cursor unless it is being managed by the application somehow (Android automagic stuff with Loaders etc.)