Query not running correctly - SQlite Android Studio

Tavian T :

I have this function that should insert data into the SQlite DB and return false if the data doesn't get inserted however the function returns true but when I go to check the .db file there's no data in the table.

public boolean insertData(String name, String emailAddress, String postalAddress, String password, int phoneNumber, String bloodType) {
    ContentValues contentValues = new ContentValues();
    SQLiteDatabase db = this.getWritableDatabase();

    //set data to columns
    contentValues.put(COL_2, name);
    contentValues.put(COL_3, emailAddress);
    contentValues.put(COL_4, postalAddress);
    contentValues.put(COL_5, password);
    contentValues.put(COL_6, phoneNumber);
    contentValues.put(COL_7, bloodType);

    //inserts data into db
    long result = db.insert(TABLE_NAME, null, contentValues);

    //checks to see if data has been inserted correctly
    if (result == -1) {
        return false;
    } else
        return true;


}

the image below shows that the table and database have been created correctly.

database info

devgianlu :

You should call #beginTransaction(), #setTransactionSuccessful() and #endTransaction() like described here.

The changes will be rolled back if any transaction is ended without being marked as clean (by calling setTransactionSuccessful).

public boolean insertData(String name, String emailAddress, String postalAddress, String password, int phoneNumber, String bloodType) {
    ContentValues contentValues = new ContentValues();
    SQLiteDatabase db = this.getWritableDatabase();

    db.beginTransaction();
    try {
        contentValues.put(COL_2, name);
        contentValues.put(COL_3, emailAddress);
        contentValues.put(COL_4, postalAddress);
        contentValues.put(COL_5, password);
        contentValues.put(COL_6, phoneNumber);
        contentValues.put(COL_7, bloodType);
        long result = db.insert(TABLE_NAME, null, contentValues);
        db.setTransactionSuccessful();
        return result != -1;
    } finally {
        db.endTransaction();
    }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=407319&siteId=1