所以我刚刚完成了我已经工作了一段时间的应用程序上的所有内容。我在控制台中遇到的唯一错误是DatabaseObjectNotClosedException。它不会导致应用程序关闭或崩溃或任何事情,但我担心这一点,因为我已经读过一个未封闭的游标可能是一个大问题。
所以这是错误信息:
05-28 20:40:01.598:E / Database(655):android.database.sqlite.DatabaseObjectNotClosedException:应用程序未关闭此处打开的游标或数据库对象
以下是它所指的代码:
datasource = new ProgressDataSource(this);
datasource.open();
以下是ProgressDataSource的代码:
package com.gauv.myapp;
import java.util.Arrays;
import java.util.Collections;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import com.jjoe64.graphview.GraphView.GraphViewData;
public class ProgressDataSource {
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
public ProgressDataSource(Context context) {
dbHelper = new MySQLiteHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public GraphViewData[] fetchProgress(long dayExerciseDataID) {
Cursor cursor = database.rawQuery("select " + MySQLiteHelper.COLUMN_1RM + " " +
"from " + MySQLiteHelper.TABLE_LOGS + " " +
"where " + MySQLiteHelper.COLUMN_ID_DAY_EXERCISE + "='" + dayExerciseDataID + "' " +
"order by " + MySQLiteHelper.COLUMN_DATE + " desc limit 30", null);
GraphViewData[] data = new GraphViewData[cursor.getCount()];
Long[] onerms = new Long[cursor.getCount()];
int i = 0;
cursor.moveToFirst();
while (cursor.isAfterLast() == false)
{
onerms[i] = cursor.getLong(0);
i++;
cursor.moveToNext();
}
Collections.reverse(Arrays.asList(onerms));
int y = 1;
for (int x = 0; x < onerms.length; x++) {
data[x] = new GraphViewData(y, onerms[x]);
y++;
}
return data;
}
public String fetchProgressCount(long dayExerciseDataID) {
Cursor cursor = database.rawQuery("select " + MySQLiteHelper.COLUMN_1RM + " " +
"from " + MySQLiteHelper.TABLE_LOGS + " " +
"where " + MySQLiteHelper.COLUMN_ID_DAY_EXERCISE + "='" + dayExerciseDataID + "' " +
"order by " + MySQLiteHelper.COLUMN_DATE + " desc limit 12", null);
return String.valueOf(cursor.getCount());
}
}
我只需要将cursor.close()
添加到fetchProgress函数吗?
答案 0 :(得分:2)
完成后你需要关闭你的数据库所以你需要做的就是调用datasource.close()
,是的你也应该关闭你不再使用的任何游标来从内存中释放它
答案 1 :(得分:0)
此错误表示您打开了数据库连接。您的代码段确认了这一点。一个好的做法是将光标中的信息导入某个域对象,然后清理光标和连接。
代码示例:
// open db connection
DataBaseHelper db = new DataBaseHelper(this);
db.open();
// retrieve your items using a cursor object
Cursor cursor = db.rawQuery("SELECT * FROM SOME_DB", null);
// iterate all your items here and move to some collection or domain model
// ...
// and clean up your mess
cursor.close();
db.close();