Elsa__fewfwef
Elsa__fewfwef

Reputation: 75

SQL - How to return a list of data

I have this SQL method below, it is suppose to return multiple rows of data, but it is only returning one item every time I try to display the data.

How do I fix that?

//Constant
    public static final String COL_4 = "LikeSong";
    

//Database Table
    @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE UserInfo(ID INTEGER PRIMARY KEY AUTOINCREMENT, Users_Name TEXT, PlaylistName TEXT,likeAlbum TEXT,LikeSong TEXT)");
        }

public String[] getLikedSongs() {
        SQLiteDatabase db = this.getReadableDatabase();
        String[] LikeSong = null;
        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);
            LikeSong = note.split(",");
        }
        cursor.close();
        db.close();
        return LikeSong;
    }

Upvotes: 2

Views: 640

Answers (2)

forpas
forpas

Reputation: 164139

Inside the while loop in each iteration you change the value of LikeSong, so when the loop ends, LikeSong has the last value assigned to it.
I think that you want a list of arrays returned by your method getLikedSongs() like this:

public List<String[]> getLikedSongs() {
        SQLiteDatabase db = this.getReadableDatabase();
        List<String[]> list = new ArrayList<>();
        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);
            LikeSong.add(note.split(","));
        }
        cursor.close();
        db.close();
        return LikeSong;
}

Upvotes: 1

Praveen Dass
Praveen Dass

Reputation: 616

Okay...now I see. You are reassigning LikeSong for each iteration of the while loop and returning the String array after the while loop has completed. So obviously, you will get value of only the last row.

Upvotes: 0

Related Questions