0

即使我在完成调用它们后立即关闭了所有实例,我也会收到以下错误:

 close() was never explicitly called on database '/data/data/com.click4tab.fragmentvogella/databases/NewOrderDB' 

 android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here

在定义此方法之前,我没有收到此错误。

public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
        case R.id.item1:
            Toast.makeText(MainActivity.this, "Button one pressed",
                    Toast.LENGTH_LONG).show();
            // write data on server
            TestAdapter mDbHelper = new TestAdapter(this);

            mDbHelper.createDatabase();
            mDbHelper.open();

            try {
                mDbHelper.writeUnwrittenNetOrder();
                mDbHelper.close();

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
                               break;

以及 writeUnwrittenNetOrder 的定义:

ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    StringBuffer strbuf = new StringBuffer();
    params.add(new BasicNameValuePair("tag", "add_NetOrderID"));

    for (mCur.moveToFirst(); !mCur.isAfterLast(); mCur.moveToNext()) {

        String sql3 = "INSERT into NetOrderID (StoreID, Date, SalesManID, NetOrderID) VALUES ("
                + mCur.getString(0)
                + ", "
                + mCur.getString(1)
                + ", "
                + mCur.getString(2) + ", " + mCur.getString(3) + ");";
         if((mCur.isLast())){
        strbuf.append(sql3);
         }
         else {
             strbuf.append(sql3 + "#");
         }
        // String sql3 =
        // "INSERT into NetOrderID (StoreID, SalesManID, NetOrderID) VALUES (1,1,80)";
        // sqlQueries.add(sql3);
        Log.e("sql", strbuf.toString());


    }


    params.add(new BasicNameValuePair("query", strbuf.toString()));
    Log.e("param","param added");

    new SyncWithServer();
    // send params
    SyncWithServer.setParams(params);
    Log.e("param","param set");

    // return arraylist
}

我应该在哪里关闭 mDbHelper 以避免此错误,当数据库成功写入且应用程序未崩溃时,Logcat 中会出现此错误。

4

2 回答 2

1

The error message says you did not close database or cursor. Did you close all of them as well (mCur object)?

于 2012-08-17T07:36:30.693 回答
0

亚历克斯提出了一个很好的观点。

而且(但我认为这不是现在导致错误的原因):我认为最好将mDbHelper.close()语句从 try/catch 中取出,或者将它放在一个finally子句中。因为目前,当writeUnwrittenNetOrder抛出异常时,mDbHelper.close()永远不会被调用。当您按照亚历克斯的建议添加游标关闭方法时,会产生类似的结果:无论打开和关闭之间发生异常,这也应该发生。

于 2012-08-17T07:42:43.563 回答