如何优化从sqlite选择数据?

时间:2018-09-01 17:10:47

标签: android sqlite

我想知道为什么查询这么慢。

// Getting all Messages from room
public JSONObject getMsgsFromRoom(String room, int limit) throws JSONException {
    JSONObject data = new JSONObject();
    JSONArray dataArray = new JSONArray();
    JSONObject wrapper = new JSONObject();
    wrapper.put(TBL_MESSAGES, dataArray);
    //Select All Query
    //        String selectQuery = "SELECT * FROM 
    "+DatabaseHandler.TBL_MESSAGES+ " WHERE "+TBL_MESSAGES_COL_PHONE_NO+" = 
    '"+room+"' LIMIT "+limit;
    String selectQuery = "SELECT * FROM "+DatabaseHandler.TBL_MESSAGES+ " 
    WHERE "+TBL_MESSAGES_COL_CHATROOM_ID+" = '"+room+"' LIMIT "+limit;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // Looping through all records and adding to list(Array List)
    if (cursor.moveToFirst()){

        JSONArray value = new JSONArray();
        JSONArray sender_id = new JSONArray();
        JSONArray sender = new JSONArray();
        JSONArray status = new JSONArray();
        for (int i=0; i < limit; i++){
            sender_id.put(cursor.getString(cursor.getColumnIndex(TBL_MESSAGES_COL_SENDER_ID)));
            if (cursor.getString(cursor.getColumnIndex(TBL_MESSAGES_COL_SENDER_ID)).equals(getAllPrefs().getString("objectId"))){
                sender.put("1");
            }else{
                sender.put("0");
            }
            value.put(cursor.getString(cursor.getColumnIndex(TBL_MESSAGES_COL_VALUE)));
            status.put(cursor.getString(cursor.getColumnIndex(TBL_MESSAGES_COL_STATUS)));
            //                Log.e(TAG, "Messages : "+ data);
            Log.e("Database Handler", "Array "+String.valueOf(i)+" : "+ value);
            cursor.moveToNext();
        }
        data.put("value", value);
        data.put("sender", sender);
        data.put("sender_id", sender_id);
        data.put("status", status);
    }
    //Closing connection
    cursor.close();
    db.close();

    // Returning Vals
    return data;
}

如何优化它,因为每次迭代将花费近500毫秒。

这是我的数据库处理程序类中的一种方法,负责通过使用房间ID过滤并有限制的消息从数据库中获取消息。

编辑

这是if语句!那么,为什么语句这么慢呢?

0 个答案:

没有答案