Search code examples
javaandroidsqliteandroid-sqliteandroid-spinner

Send spinner data to database


I am trying to send data to database from a spinner I initialize the database like this SPINNER + " TYPE ";

And in insert data method I put it as Type spinner but this line gives me an error contentValues.put(SPINNER, spinner);

what should I put there instead of put

public boolean insertData(String fname, String lname, String pnumber, String email, String nic, Type spinner) {
            SQLiteDatabase db = this.getWritableDatabase();
            ContentValues contentValues = new ContentValues();
            contentValues.put(FNAME, fname);
            contentValues.put(LNAME, lname);
            contentValues.put(PNUMBER, pnumber);
            contentValues.put(EMAIL, email);
            contentValues.put(NIC, nic);
            contentValues.put(SPINNER, spinner);

            long result = db.insert(DB_TABLE, null, contentValues);
            return result != -1;
        }

Solution

  • You are trying to save a spinner object in the database which of course fails.
    Change the data type of the column SPINNER to TEXT in the table:

    ...SPINNER + " TEXT";
    

    Also change the data type of the argument spinner to String in the definition of insertData():

    public boolean insertData(String fname, String lname, String pnumber, String email, String nic, String spinner)
    

    When you call insertData() pass the selected item of the spinner instead of the spinner itself:

    insertData(....., yourSpinner.getSelectedItem().toString()) 
    

    Now uninstall the app from the device to delete the database and rerun so it is recreated with the proper data type for the column SPINNER.