Reputation: 157
I have a function that fetches the id for a song. The id is a primary field and autoincrement. But somehow whenever I call this function it returns me -1 that is result not found. Is there something wrong with how I am approaching the problem?
int getIdForSong(Song song){
String selectQuery = "SELECT id FROM " + TABLE_SONG + " WHERE " + SONG_TITLE + "= ' " + song.getSongTitle() + "' AND " + ARTIST_NAME + "= ' " + song.getArtistName()+" ' ";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToFirst();
if(cursor.moveToNext() && cursor != null){
int id = Integer.parseInt(cursor.getString(0));
return id;
}
else
return -1;
}
Upvotes: 1
Views: 71
Reputation: 6640
I see extra spaces:
' " + song.getArtistName()+" '
So if your Artist name is "Green Day" it becomes " Green Day "
Similarly:
"= ' " + song.getSongTitle() + "'
So "Boulevard Of Broken Dreams" becomes " Boulevard Of Broken Dreams"
Upvotes: 3
Reputation: 1667
String selectQuery = "SELECT id FROM " + TABLE_SONG + " WHERE " + SONG_TITLE + "= '" + song.getSongTitle() + "' AND " + ARTIST_NAME + "= '" + song.getArtistName()+"' ";
Upvotes: 0