Skip to content
Advertisement

Android studio SQL – How to return data in a string array

I have an SQL method here. I would like to return the data in a String[] array.

How do I do that exactly?

Thank you!

public String[] getLikedSongs() {
        SQLiteDatabase db = this.getReadableDatabase();
        String[] LikeSong;
        Cursor cursor = db.rawQuery(" SELECT " + COL_4 + " FROM " + Table_Name + " WHERE " + COL_4 + " IS NOT NULL", null);
        while (cursor.moveToNext()) {
            String note = cursor.getString(0);
        }
        cursor.close();
        db.close();
        return LikeSong;
    }

Advertisement

Answer

You must define the array’s length and this can be done only after the Cursor fetches all the rows. Then set its length to the nimber of rows of the Cursor.
Then inside the while loop set the items of the array:

public String[] getLikedSongs() {
    String[] LikeSong = null;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT " + COL_4 + " FROM " + Table_Name + " WHERE " + COL_4 + " IS NOT NULL", null);
    if (cursor.getCount() > 0) {
        LikeSong = new String[cursor.getCount()];
        int i = 0;
        while (cursor.moveToNext()) {
            LikeSong[i] = cursor.getString(0);
            i++;
        }
    }
    cursor.close();
    db.close();
    return LikeSong;
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement