簡體   English   中英

在Android中從SQLite數據庫創建字符串數組

[英]Create a String array from a SQLite DB in Android

我需要生成一個如下所示的數組:

String[] testlist = new String[] {"First Note", "Second Note", "Third Note"};

我需要的信息在SQLite數據庫內部。 我正在使用以下代碼進行訪問:

db = new notesDBHelper(this);

//notesDBHelper is a standard SQLiteHelper, the DB has a table called notes with fields 'title' and 'note_text'

String query = String.format("SELECT * FROM notes");
db.getReadableDatabase().rawQuery(query, null);

這就是我被卡住的地方-查詢返回沒有錯誤,但是我不確定構建字符串的語法。

可以使用列表代替數組。 比起您不必設置大小。

ArrayList<String> list = new ArrayList<String>();
String[] array = new String[4]
int counter = 0;

String query = String.format("SELECT * FROM notes");
Cursor cursor  = db.getReadableDatabase().rawQuery(query, null);

while (cursor.moveToNext()) {
    String note = cursor.getString(1);
    list.add(note);

    if(counter < array.length){
       array[counter] = note;
       counter++;
    }
}

現在,我將兩種解決方案都放入了代碼中。 您還必須確定它是哪一行。

您應該在查詢中使用游標。 這樣的功能(從頭開始的未經調試的代碼)可以在數據庫幫助程序類中使用。

public ArrayList<String> getStrings() {

  ArrayList<String> strings = new ArrayList<String>();
  String query = String.format("SELECT * FROM notes");
  Cursor c = db.getReadableDatabase().rawQuery(query, null);

  if (c.moveToFirst())
            do {
                strings.add(sessionCursor.getString(1)); // 1 = columnindex
            } while (sessionCursor.moveToNext());   

  return strings;

}

暫無
暫無

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

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