insert data date sqlite - java

Asked

Viewed 26 times

0

Hi, I am trying to pass a date set by the user to the database, but whenever I click add the application crasha and I have the following error:

java.lang.Illegalargumentexception: Cannot format Given Object as a Date.

The code to add the data to the BD is:

 public void add(String date){
     
        SQLiteDatabase db = this.getWritableDatabase();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        ContentValues cv = new ContentValues();
        cv.put(COLUMN_DATE, dateFormat.format(date));

And this is the code I have in Activity, to call the datepickerdialog and pass the entered data to the method that adds the information to db.

datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                Calendar dataSelect = Calendar.getInstance();
                dataSelect.set(year,month,dayOfMonth);
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                adddate.setText(format.format(dataSelect.getTime()));
            }
        },calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH));

        adddate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                datePickerDialog.show();
            }
        });

        btnsubtmit = findViewById(R.id.btnadd);

        btnsubtmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DataBase myDB = new DataBase(AddTarefas.this);
                myDB.add(adddate.getText().toString().trim());
            }
        });

1 answer

0

// o correto para transformar uma string em um date é usar o parse
public void add(String date) {
    SQLiteDatabase db = this.getWritableDatabase();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    try {
        ContentValues cv = new ContentValues();
        cv.put(COLUMN_DATE, dateFormat.parse(date));
    } catch (ParseException e) {
        e.printStackTrace();
    }

}

As Voce calls a Datepickerdialog, I would say to Voce change the field adddate for a Textview, and store the result of onDateSet() in a variable Date, and go to db

Browser other questions tagged

You are not signed in. Login or sign up in order to post.