Search code examples
androidandroid-sqlitesqldelight

Sqlite insert lines bug


I am stuck on a really weird bug. I have a table followers, and when I insert datas, it works except for th me first entry.

The first time I call the function, nothing is thrown and the insert function return as expected 1. But when I call the select all function, the table is empty.

However when I call the function an other time with different parameters, the data are really inserted and the table shows one entry (this one) but with 2 as id.

I am using Sqldelight.

public long insertFollower(String name, String wca_id, long created_at) {

    try {
        SQLiteDatabase db = openDatabase();

        return db.insert(Follower.TABLE_NAME, null, Follower.FACTORY.marshal()
                .name(name)
                .wca_id(wca_id)
                .created_at(created_at)
                .asContentValues());
    }

    catch (Exception e) {
        e.printStackTrace();
    }

    finally {
        closeDatabase();
    }

    return 0;
}

private static AtomicInteger openCount = new AtomicInteger();
private static SQLiteDatabase database;

public static final String DATABASE_NAME = "database.db";
public static final int DATABASE_VERSION = 12;

private static DatabaseHelper instance;

public static synchronized DatabaseHelper getInstance(Context context) {
    if(instance == null) {
        instance = new DatabaseHelper(context);
    }

    return instance;
}

public synchronized SQLiteDatabase openDatabase() {
    if(openCount.incrementAndGet() == 1) {
        database = getWritableDatabase();
    }

    return database;
}

public synchronized void closeDatabase() {
    if(openCount.decrementAndGet() == 0) {
        database.close();
    }
}


@Override
public void onCreate(SQLiteDatabase db) {

    db.execSQL(Follower.CREATE_TABLE);
    db.execSQL(Record.CREATE_TABLE);

}

And the Follower.CREATE_TABLE who was generated by sqldelight

  String CREATE_TABLE = ""
  + "CREATE TABLE follower (\r\n"
  + "    _id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\r\n"
  + "    name TEXT NOT NULL,\r\n"
  + "    wca_id TEXT NOT NULL\r\n"
  + ")";

EDIT :

I noticed something strange that may help:

This works only if the table is empty

I insert a follower, that doesn't works. But when I insert an other follower with the same ID as the first one (there is a primary key autoincrement). I get a UNIQUE exception but the table is still empty.

Do not hesitate to ask more information.

Thank you.


Solution

  • I finally find the answer thanks to @anstrong: to select the follower I used cursor.moveToFirst() and the while(cursor.moveToNext()) was called just after