Search code examples
javaandroidsqliteandroid-sqlite

How to use insert() method about sqlite Database in android


Here's my code (MainActivity.java.OnCreate):

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //creating a database
    SQLiteDatabase sqLiteDatabase=this.openOrCreateDatabase("DB_NAME",MODE_PRIVATE,null);
    //creating a table with one column named 'column' inside of it.
    sqLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS tb_name('column'VARCHAR)");
    //creating an OnClickListener for a simple button(I havent included the activity_main.xml but I dont think that it is necessary)
    Button button=(Button)findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ContentValues contentValues=new ContentValues();
            contentValues.put("column","this item is inserted");
            sqLiteDatabase.insert("table",null,contentValues);
            long valueOfInsertion = sqLiteDatabase.insert("table",null,contentValues);
            Log.i("button","value of insertion: "+ valueOfInsertion);





        }
    });
}```

but I keep getting value -1 from logcat (check line 18 of my code for more info) and an Exception:

2021-01-16 22:33:58.162 9051-9051/com.rahgozar.d2 E/SQLiteDatabase: Error inserting column=this item is inserted
    android.database.sqlite.SQLiteException: near "table": syntax error (code 1 SQLITE_ERROR): , while compiling: INSERT INTO table(column) VALUES (?)
        at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
        at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1045)
        at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:652)
        at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:590)
        at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:61)
        at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:33)
        at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1699)
        at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1570)
        at com.rahgozar.d2.MainActivity$1.onClick(MainActivity.java:30)
        at android.view.View.performClick(View.java:7448)
        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:992)
        at android.view.View.performClickInternal(View.java:7425)
        at android.view.View.access$3600(View.java:810)
        at android.view.View$PerformClick.run(View.java:28305)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

Important note: Exception only happen when I click the button (calling OnClickListener);


Solution

  • The table's name is tb_name and not table.
    Also it is not a good practice to use a keyword like column for identifiers such like a column's name.
    Finally there is no VARCHAR data type in SQLite. You can use TEXT.

    So, for the creation of the table you can do:

    sqLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS tb_name(columnName TEXT)");
    

    Change columnName to a meaningful name (there is no need for single quotes).

    And insert the new row with:

    ContentValues contentValues = new ContentValues();
    contentValues.put("columnName", "this item is inserted");
    sqLiteDatabase.insert("tb_name", null, contentValues);
    

    After these changes are done you may have to uninstall the app from the device and rerun.