如果需要,我使用以下方法更新数据库,数据从网络服务中检索为JSONObject
. 但似乎这个方法只是停止工作database.update
(这行代码之后的日志没有出现在logcat上,并且logcat没有报告错误,很奇怪!)
private void updateDB(JSONArray serverRecords) throws JSONException {
Log.i(LOGTAG, "update db started");
for (int i = 0; i < serverRecords.length(); i++) {
JSONObject row = serverRecords.getJSONObject(i);
String pin = row.getString("pin");
String state = isRecordUnique(pin);
Log.i(LOGTAG, "State => " + state);
if (state.equals("0")) {
//makeDbReady();
Log.i(LOGTAG, "new record");
// new record
ContentValues inserts = new ContentValues();
inserts.put(SQLiteHelper.COLUMN_CARD_OPERATOR,
row.getInt("opr"));
inserts.put(SQLiteHelper.COLUMN_CARD_TYPE, row.getString("typ"));
inserts.put(SQLiteHelper.COLUMN_CARD_PIN, row.getString("pin"));
inserts.put(SQLiteHelper.COLUMN_CARD_PRICE,
row.getString("pri"));
inserts.put(SQLiteHelper.COLUMN_DATE, row.getString("dte"));
inserts.put(SQLiteHelper.COLUMN_STATE, row.getInt("stt"));
inserts.put(SQLiteHelper.COLUMN_SYNC_DATE, row.getString("syn"));
long affected = database.insert(SQLiteHelper.TABLE_NAME, null,
inserts);
Log.i(LOGTAG, "datbase updated and " + affected
+ " rows affected");
} else {
//makeDbReady();
Log.i(LOGTAG, "update record, sync date => ");
// update existing records
ContentValues values = new ContentValues();
values.put(SQLiteHelper.COLUMN_SYNC_DATE, row.getString("syn"));
values.put(SQLiteHelper.COLUMN_STATE, row.getInt("stt"));
Log.i(LOGTAG, "Values: " + values.toString());
try {
int affected = database.update(SQLiteHelper.TABLE_NAME, values,
SQLiteHelper.COLUMN_ID + " = '" + row.getString("_id")
+ "'", null);
} catch (SQLiteException e) {
Log.i(LOGTAG, e.getMessage());
}
// String sqlQuery = "UPDATE `" + SQLiteHelper.TABLE_NAME
// + "` SET `" + SQLiteHelper.COLUMN_STATE + "` = '"
// + row.getInt("stt") + "', `"
// + SQLiteHelper.COLUMN_STATE + "` = '"
// + row.getInt("stt") + "' " + "WHERE _id ='"
// + row.getString("_id") + "'";
// Log.i(LOGTAG, sqlQuery);
// database.execSQL(sqlQuery);
Log.i(LOGTAG, "update sate: ");
}
Log.i(LOGTAG, "update method: condition did not met");
}
}
我还尝试关闭Cursor
代码中的每个对象实例。唯一可能的“左打开”游标对象是那些传递给处理方法的对象,我不知道它会导致错误,但我还注释了调用该方法的代码行(以确保Cursor
之前没有打开任何对象试图更新)但它没有任何区别。
这是日志:
07-02 16:20:45.307: I/myapp(13928): update db started
07-02 16:20:45.317: I/myapp(13928): State => 4
07-02 16:20:45.317: I/myapp(13928): update record, sync date =>
07-02 16:20:45.317: I/myapp(13928): Values: state=1 sync_date=13-07-02 13:26:31
SQLiteHelper.COLUMN_ID
是一个常数,其值为:_id