[英]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. 我需要的信息在SQLite数据库内部。 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.