Zion Q Zion Q - 5 months ago 31
Java Question

Can't I save objects into sqlite in my android app

I tried to save an object into sqlite, and the class of the object has implemented Serializable. But there is always an error:

android.database.sqlite.SQLiteException: unrecognized token:
"[Ljava.lang.Object;@277c81d9" (code 1): , while compiling: insert
into mClass(classData) values(?)[Ljava.lang.Object;@277c81d9

Here is my code:

public boolean add(ReturnInfo ri) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
db = dh.getWritableDatabase();
ObjectOutputStream oos = new ObjectOutputStream(bos);
byte[] data = bos.toByteArray();
db.execSQL("insert into mClass(classData) values(?)" + new Object[]{data});
Log.e("db", "insert succeeded");
return true;
} catch (Exception e) {
Log.e("db", "insert failed");
return false;

The database has been created successfully, I have no idea where went wrong.


The issue is that you use prepared statements in a wrong way.

db.execSQL("insert into mClass(classData) values(?)" + new Object[]{data});

Here you generate inappropriate SQL statement because you just add an object to the end of the string and end up with something like this:

"insert into mClass(classData) values(?)[Ljava.lang.Object;@277c81d9"

which is not an SQL statement.

To use prepared statements you need write the following:

SQLiteStatement stmt = 
    db.compileStatement("insert into mClass(classData) values(?)");
stmt.bindString(1, data);

Also, look at this question to get a better understanding of prepared statements in android.