Error with SQLite in Android

191 views Asked by At
06-19 12:36:06.181: E/Inside log(15543): /sdcard/songs/(04) Fall Out Boy - Sugar, We're Goin' Down [2005].mp3
06-19 12:36:06.286: E/IMediaMetadataRetriever(15543): extractMetadata error
06-19 12:36:06.391: E/SQLiteLog(15543): (1) near "re": syntax error
06-19 12:36:06.421: E/AndroidRuntime(15543): FATAL EXCEPTION: main
06-19 12:36:06.421: E/AndroidRuntime(15543): android.database.sqlite.SQLiteException: near "re": syntax error (code 1): , while compiling: insert into SongDataBase(name,artist,genre,composer,albumname,year,path) values('Sugar, We're Goin' Down','Fall Out Boy','Punk','null','From Under The Cork Tree','2005','/sdcard/songs/(04) Fall Out Boy - Sugar, We're Goin' Down [2005].mp3')

Code:

if(name!=null)
{
    if(name.contains("'"))
    {
        name.replaceAll("'", "\'");
    }
}
if(genre!=null)
{
    if(genre.contains("'"))
    {
        genre.replaceAll("'", "\'");
    }
}
if(composer!=null)
{
    if(composer.contains("'"))
    {
        composer.replaceAll("'", "\'");
    }
}
if(albumname!=null)
{
    SQLiteDatabase database=getWritableDatabase();
    database.execSQL("insert into SongDataBase(name,artist,genre,composer,albumname,year,path) values('"+name+"','"+artist+"','"+genre+"','"+composer+"','"+albumname+"','"+yea‌​r+"','"+pathfile+"')");
}
2

There are 2 answers

1
Phantômaxx On

You need to double ('') the apostrophes (') in your strings.
Otherwise, they will be treated as string delimiters, breaking your string values.

A better solution, though, would be to pass bound parameters (using the ? placeholders, which will be then filled by the values stored in a string array you would pass).
This way, the string conversion is handles automatically, and you don't have to double the quotes.


OK, by analyzing your code, the problem pops out very clearly:
You don't perform the quote replacement on the Artist, the Album Name and on the File Path.
You only do that on Name, Genre and Composer.

In your case, the path is giving you the error.

It's clear from this error message:

/sdcard/songs/(04) Fall Out Boy - Sugar, We're Goin' Down [2005].mp3
0
Rumpelstinsk On

When you ask a question you should provide more info (sample code, etc.). However you problem is quite clear, you only have to see the log file:

android.database.sqlite.SQLiteException: near "re": syntax error (code 1): , while compiling: insert into SongDataBase(name,artist,genre,composer,albumname,year,path) values('Sugar, We're Goin' Down','Fall Out Boy','Pu

You need to escape the character ' in the piece of code you use to create that query. If you don't provide sample code I can't be more specific. But it's quite simple to resolve.