简体   繁体   中英

Create a String array from a SQLite DB in Android

I need to generate an array that looks like the following:

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

The information I need is inside a SQLite Database. I'm using the following code to access:

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);

This is the point where I'm stuck - The query returns without error, but I'm not sure of the syntax to build the string.

Instead of a array you can use a list. Than you don't have to set a size.

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++;
    }
}

Now I put both solution in the code. You have also to decide which row it is.

You should use a cursor with your query. A function like this (untested code from the top of the head) could work in your database helper class.

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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM