【发布时间】:2021-07-10 08:09:50
【问题描述】:
我正在尝试从表中选择所有列并将所有行返回到游标中,然后遍历游标以获取列并使用列名从每列中获取值。然后将列名及其值放入 JSONObject。但我不断收到 CursorIndexOutOfBoundException。有没有办法我可以选择未知数量的列和行并将每个映射到一个键值对。 下面是我的代码
public JSONObject getAllCompanies() {
JSONObject response = new JSONObject();
try {
SQLiteDatabase sqLiteDatabase = dbHelper.getWritableDatabase();
JSONArray dataArray = new JSONArray();
JSONObject dataObject = new JSONObject();
Cursor companyCursor = sqLiteDatabase.rawQuery("SELECT * FROM COMPANY", null);
if (companyCursor.moveToFirst()) {
do {
String column = "";
String value = "";
for (int m = 0; m < companyCursor.getColumnCount(); m++) {
column = companyCursor.getColumnName(m);
value = companyCursor.getString(companyCursor.getColumnIndex(value));
Log.i("COLUMN", column + " COLUMN VALUE: " + value);
dataArray.put(new JSONObject()
.put(column, value));
}
}
while (companyCursor.moveToNext());
// dataArray.put(dataObject);
response.put("success", true);
response.put("statuscode", 200);
response.put("payload", dataArray);
}
} catch (JSONException e) {
e.printStackTrace();
}
dbHelper.close();
return response;
}
【问题讨论】:
标签: java android json sqlite android-cursor