P
P
pmozil2016-06-07 00:48:27
Android
pmozil, 2016-06-07 00:48:27

Why does adding a row to the database using the insert method in Android return a row ID of -1?

Body of OnClick method:

ContentValues cv = new ContentValues();
        String sum = tvSum.getText().toString();
        String sp = spinner.getSelectedItem().toString();

        SQLiteDatabase db = dbHelper.getWritableDatabase();

        cv.put("suma",sum);
        cv.put("valuta",sp);
   

        long rowID = db.insert("mytable", null, cv);
       
         Log.d(TAG, "row inserted, ID = " + rowID);  //в этом месте rowID равен -1 
//и база данных остается пустой


        Cursor c = db.query("mytable", null, null, null, null, null, null);

        if (c.moveToFirst()) {

            int idColIndex = c.getColumnIndex("id");
            int sumColIndex = c.getColumnIndex("suma");
            int valColIndex = c.getColumnIndex("valuta");
            do {
                Log.d(TAG,
                        "ID = " + c.getInt(idColIndex) +
                                ", suma = " + c.getString(sumColIndex) +
                                ", valuta = " + c.getString(valColIndex));
            } while (c.moveToNext());
        } else
            Log.d(TAG, "0 rows"); // и естественно я вижу только "0 rows",так как moveToFirst() 
//не нашел ни одной записи.
        c.close();


    }

    class DBHelper extends SQLiteOpenHelper {

        public DBHelper(Context context) {
            super(context, "myDB", null, 1);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            Log.d(TAG, "--- onCreate database ---");
            db.execSQL("create table mytable ("
                    + "id integer primary key autoincrement,"
                    + "suma text,"
                    + "valuta text" + ");");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        }
    }

I don't understand if the record is not added because insert doesn't work? Or is there an error in another part of the code?
Please help me find the error, otherwise I have been suffering for the second day.
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Perelygin, 2016-06-22
@orcDamnar

when writing to the database, it is necessary to ensure that the work with the database occurs from one thread. I recommend that you make a SingleInstance for the helper and get the writable database instance via getInstance(). In addition, try pushing the insert into a transaction. Also, if you create "id integer primary key autoincrement," it should be _id instead of id.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question