Devil Raily Devil Raily - 22 days ago 6
Android Question

Format database results as comma separated

Following the tutorial from this question on Stackoverflow. After querying the database, I have records in variable

results
. How do I format the results so that it can be a array. Below is an example:

lvActivityCategory.setAdapter(new categoryCursorAdaptor(this, new String[] { "data1", "data2" }));


This is the code that am currently working with:

List<String> arrayCatNames = new ArrayList<String>();
String query = "SELECT * FROM category ORDER BY name ASC";
Cursor results = myDB.rawQuery(query, null);
while(results.moveToNext()){
String catName = results.getString(results.getColumnIndex("name"));
arrayCatNames.add(catName);
}
android.text.TextUtils.join(",", arrayCatNames);
lvActivityCategory = (ListView) findViewById(R.id.lvActivityCategory);
lvActivityCategory.setAdapter(new categoryCursorAdaptor(this, new String[] { arrayCatNames })); //arrayCatNames should be e.g. "item 1", "item 2", "item 3"

Answer

Ok, do this below, after your while loop

String[] catNamesArr = new String[arrayCatNames.size()];
catNamesArr = arrayCatNames.toArray(catNamesArr);

You can learn more reading this question: Convert ArrayList<String> to String[] array