我收到跟踪错误,即使我在完成呼叫后立即关闭了所有实例:
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中会出现此错误。
答案 0 :(得分:1)
错误消息显示您未关闭数据库或光标。您是否也关闭了所有这些(mCur
对象)?
答案 1 :(得分:0)
并且(但我认为这不是导致错误的原因):我认为最好从try / catch中取出mDbHelper.close()
语句,或者将其放在{{1子句。因为目前,当finally
抛出异常时,永远不会调用writeUnwrittenNetOrder
。当您按照Alex建议添加光标关闭方法时,可比较的东西会产生:无论打开和关闭之间发生异常,这都应该发生。