samedi 27 février 2016

Why is this SQLite database not getting populated only on the first try?

Firstly, my SQLite database has just a single row. I have 2 menu items, action_refresh is supposed to update this single row. It does this HOWEVER, only on the second click, after app startup.

    if (id == R.id.action_refresh) {
        new ParseJson().execute();
        Products product = new Products(json2);
        dbHandler.addProduct(1, product);
        Toast.makeText(MainActivity.this, dbHandler.databaseToString() , Toast.LENGTH_SHORT).show();
        return true;
    }

When I use make_null set the item to null, and hit action_refresh again, this time the database is populated on first try!

    if (id == R.id.make_null) {
        Products product = new Products(null);
        dbHandler.addProduct(1, product);
        Toast.makeText(MainActivity.this, dbHandler.databaseToString() , Toast.LENGTH_SHORT).show();
        return true;
    }

What is even more confusing is that if I already have json2 stored in my database, upon app restart, it is still there. When I hit action_refresh the first time, data is cleared, and it is as though I had updated json2 with null even though json2 is never null. Hit action_refresh a a second time and json2 gets stored back!

Maybe it has something to do with the addProduct function?

public void addProduct(int id, Products product){
    ContentValues values = new ContentValues();
    values.put(COLUMN_ID, id);
    values.put(COLUMN_PRODUCTNAME, product.get_productname());
    SQLiteDatabase db = getWritableDatabase();
    db.replace(TABLE_PRODUCTS, null, values);
    db.close();
}

Or how the table is created?

public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
    super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String query = "CREATE TABLE " + TABLE_PRODUCTS + "(" +
            COLUMN_ID + " INTEGER PRIMARY KEY DEFAULT 1, " +
            COLUMN_PRODUCTNAME + " TEXT " +
            ");";
    db.execSQL(query);
}

I just cannot see it. Where are things going wrong? Please let me know if you would like to look at other parts of the code.

Aucun commentaire:

Enregistrer un commentaire