Reputation: 13
I got a big problem here. I create databasehelper class to handle all of my query function. Now I try to make a function that will load all values of a column from my database but I dont know how to do it. FYI I got 3 columns inside my database table. Here is my code so far:
(UPDATED, it works and gives me values now)
public List<Content> getSearchKeys() {
List<Content> contentList = new ArrayList<Content>();
// The query
String selectQuery = "SELECT * FROM " + TABLE_SEARCH;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// I use do.. while here and it works now, should I better use for loop?
if (cursor.moveToFirst()) {
do {
Content content = new Content();
content.setID(Integer.parseInt(cursor.getString(0)));
content.setsKeys(cursor.getString(1));
content.setAct(cursor.getString(2));
// Adding content to list
contentList.add(content);
} while (cursor.moveToNext());
}
// return content list
return contentList;
}
The problem now is how to pass the result of above function into String[] ? In my Activity I try to use it like this and it's not working:
(Updated)
...
setContentView(R.layout.page_search);
DatabaseHandler db = new DatabaseHandler(this);
List<Content> contents = db.getAllContacts();
final String[] searchQ = new String[contents.size()];
int i =0;
for (Content cn : contents) {
searchQ[i] = cn.getsKeys().toString();
}
final String[] SearchQueries = searchQ;
If I comment the code above and change it to string array like this, then it works:
static final String[] SearchQueries = new String[] { "iPhone", "Mac", "Apple",};
My aim is to replace array above into Array I retrieve from my database. So what's wrong and what's the correct method to handle this? Many thanks for your help.
Upvotes: 1
Views: 1472
Reputation: 28561
Problem 1: if cursor is empty but not null, your do while loop fails (change it to a while loop)
Problem 2: to convert to string, you'll need a toString
method in your Content
class. Then you will write a loop:
String[] queryAsStrings = new String[query.size()];
int i = 0;
for (Content c : query) {
queryAsStrings[i] = c.toString();
}
Upvotes: 1