如何正确关闭Android Java游标

时间:2012-12-29 16:36:15

标签: java android

如果我尝试在方法onSets.close();中使用getData()关闭光标,则数据不会出现在该位置。如果我不关闭游标方法,那么Eclipse会抱怨并说基座或游标未关闭。 但是,如果我在方法c.moveToFirst();中添加一行getSets(String toexes_ids, String toprog_dif),则不会出现错误。这是为什么?  我有两种方法:

MyDatabase.java中的一个方法

public Cursor getSets(String toexes_ids, String toprog_dif) {
  SQLiteDatabase db = getReadableDatabase();
  SQLiteQueryBuilder qb = new SQLiteQueryBuilder();     
  String [] sqlSelect = {"_id", "exes_ids", "sets_ids", "sets_weight", "sets_ones"}; 
  String sqlTables = "Sets";
  String selection = "exes_ids = " + toexes_ids + " AND " + "prog_dif = " + toprog_dif;
  qb.setTables(sqlTables);
  Cursor c = qb.query(db, sqlSelect, selection, null, null, null, null);
  c.moveToFirst();
  return c;
  }

MainActivity.java中的第二个方法

public void getData() {
  db = new MyDatabase(this);
  onSets = db.getSets(toexes_ids, toprog_dif);
  ListAdapter adapter = new SimpleCursorAdapter(this, 
    R.layout.itemsets, onSets, 
    new String[] {"sets_ids", "sets_weight", "sets_ones"},  
    new int[] {R.id.itemsets_ids, R.id.itemsets_weight, R.id.itemsets_ones});
  listSets.setAdapter(adapter);
  db.close();
    }

错误:

12-29 16:17:09.335: D/dalvikvm(571): GC_CONCURRENT freed 393K, 53% free 2759K/5767K, external 1574K/1802K, paused 5ms+10ms
12-29 16:17:09.355: E/Database(571): close() was never explicitly called on database '/data/data/com.exp.exp_betta/databases/fitsdbsqlite3' 
12-29 16:17:09.355: E/Database(571): android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
12-29 16:17:09.355: E/Database(571): at android.database.sqlite.SQLiteDatabase.<init>(SQLiteDatabase.java:1847)

2 个答案:

答案 0 :(得分:0)

尝试从中获取数据后立即关闭数据库连接。保持打开状态使数据库泄露,这就是为什么Eclipse抛出错误而不关闭DatabaseObjectNotClosedException

public Cursor getSets(String toexes_ids, String toprog_dif) {
  SQLiteDatabase db=getReadableDatabase();
  //Querying the database
   db.close(); //as you get the cursor you can now close the connection here.
  return cursor;
 }

public void getData()
 {
  }

答案 1 :(得分:0)

我认为您需要关闭在getSets()方法

中创建的数据库实例