簡體   English   中英

有沒有辦法我可以使用 android-sqlite cursor 從列數未知的表中 select *

[英]Is there a way I can select * from a table with unkown number of columns using an android-sqlite cursor

我正在嘗試 select 表中的所有列並將所有行返回到 cursor 然后循環通過 cursor 從每個列中獲取值並使用列名來獲取列名。 然后將列名及其值放入 JSONObject。 但我不斷收到 CursorIndexOutOfBoundException。 有沒有辦法可以將 select 未知的列數和行數和 map 分別放入一個鍵值對。 下面是我的代碼

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;
}
 value = companyCursor.getString(companyCursor.getColumnIndex(value));

這里getColumnIndex(value)value = ""返回 -1,這不是一個有效的索引。 由於您已經在m中擁有索引,因此您可以使用

value = companyCursor.getString(m);

getColumnIndex()方法需要列的名稱作為參數。
列的名稱存儲在變量column而不是value中。
改成:

value = companyCursor.getString(companyCursor.getColumnIndex(column));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM