0

I have problem with inserting row into db table. I've following code:

try {
  myDB = jDB.getInstance(getApplicationContext()).db;

  myDB.beginTransaction();
  String sSQL = "INSERT INTO kosik (mnozstvi, cena, idVyrobek) VALUES ('" +
          sMn + "', '" + sCena + "', '" + String.valueOf(iIDVyrobku) + "');";
  myDB.execSQL(sSQL, null);
  myDB.endTransaction();
} catch (SQLiteException e) {
  e.printStackTrace();
}

Class jDB is following:

public class jDB {
private static jDB dbInstance = null;
public static String DB_PATH;
public static SQLiteDatabase db = null;
private static final String DATABASE_NAME = "db.sqlite";
.
.
.
public static jDB getInstance(Context context)
{
if (dbInstance  == null) 
{
  DB_PATH = "/data/data/" + context.getPackageName();
  // if not exists database, copy new from assets
  if (!isDataBaseExist())
  {
    try {
      copyDataBase(context);
    } catch (IOException ex)
    {
      Toast.makeText(context,
          "" + ex.getLocalizedMessage(), Toast.LENGTH_LONG).show();
    }
  }
  DB_PATH = DB_PATH + "/" + DATABASE_NAME;
  db = SQLiteDatabase.openDatabase(DB_PATH, null, SQLiteDatabase.OPEN_READWRITE);
  // create singleton object
  dbInstance = new jDB(context);
}
return dbInstance;
}

After insert, everything seems OK, but no row is inserted into table...

What I'm doing wrong ?

Thanks, Petr

SOLUTION:

Finally, there is working solution:

try {
    myDB = jDB.getInstance(getApplicationContext()).db;

    myDB.beginTransaction();
    ContentValues insertValues = new ContentValues();
    insertValues.put("idVyrobek", String.valueOf(iIDVyrobku));
    insertValues.put("mnozstvi", sMn);
    insertValues.put("cena", sCena);
    insertValues.put("poznamka", "");
    myDB.insertOrThrow("kosik", null, insertValues);
    myDB.setTransactionSuccessful();
  } catch (SQLiteException e) {
    e.printStackTrace();
  } finally {
    myDB.endTransaction();
}

Thanks a lot for your help Bismark !

1 Answer 1

1

Try to add setTransactionSuccessful() before call endTransaction(). Also I usually put the endTransaction at finally statement to avoid issues with SQLite:

myDB = jDB.getInstance(getApplicationContext()).db;
myDB.beginTransaction();
try {
    String sSQL = "INSERT INTO kosik (mnozstvi, cena, idVyrobek) VALUES ('" +
          sMn + "', '" + sCena + "', '" + String.valueOf(iIDVyrobku) + "');";
    myDB.execSQL(sSQL, null);
    myDB.setTransactionSuccessful();
} catch (SQLiteException e) {
    e.printStackTrace();
} finally {
    myDB.endTransaction();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, setTransactionSuccessful() was one piece in puzzle :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.