Bifrost51
Bifrost51

Reputation: 26

Android: Sqlite insert in database only after user saves

My app lets the user modify information that affects several rows. The user can modify several of these, but I just want the changes to be applied to the database if the user chooses to save (He can discard changes) I'm having some issues with this.

Right now I'm trying to use values.put and then calling db.insert in the save onClickListener, but if the user changes more than one row, this would only reflect the last change the user made, right? (A row consists of name, date, spinnerGeneral, spinnerSprint, timeSprint, spinnerRest, timeRest) How can I deal with this? An array of values and then call insert for each one of them?

this is my code now

values.put( "name", workoutName );
values.put( "date",datewo );
values.put( "spinnerGeneral", data.get(1).getSpinnerGeneral() );
values.put( "spinnerSprint", data.get(1).getSpinnerSprint() );
values.put( "timeSprint", data.get(1).getTimeSprint() );
values.put( "spinnerRest", data.get(1).getSpinnerRest() );
values.put( "timeRest", data.get(1).getTimeRest() );


[....]


@Override
public boolean onOptionsItemSelected(MenuItem item) {
    saveData=true;
    int id = item.getItemId();

if (id == R.id.action_save){
    long rowId = db.insert("workout",null,values); 
    onBackPressed();
}

I also thought about just calling db.insert() when the user first modifies a row, and saving the row_ID into an array rowID[], and if the user decides to discard changes, just delete all the rows with the row_ID that I have. Is this possible? Would it just be using a DELETE * FROM workout WHERE Row_ID=rowID[1...]? Is Row_ID the name of the column that it generates automatically?

Thank you very much

Upvotes: 0

Views: 54

Answers (1)

Gary Bak
Gary Bak

Reputation: 4798

For starters, I'd model my database after real life objects, not UI components, leaving the spinner name out of the DB column name, unless you of course speaking of a bicycle spinning workout.

I'd advise against adding data and then removing it again if the user decides to discard the data. It adds unnecessary complexity.

Working off what little code you supplied, I'd think the solution would be something like this:

private void collectUIValues() {
   values.clear();
   values.put( "name", workoutName );
   values.put( "date",datewo );
   values.put( "spinnerGeneral", data.get(1).getSpinnerGeneral() );
   values.put( "spinnerSprint", data.get(1).getSpinnerSprint() );
   values.put( "timeSprint", data.get(1).getTimeSprint() );
   values.put( "spinnerRest", data.get(1).getSpinnerRest() );
   values.put( "timeRest", data.get(1).getTimeRest() );
}

if (id == R.id.action_save){
    collectUIValues();        
    long rowId = db.insert("workout",null,values); 

    onBackPressed();
}

BTW, I always try to use an ORM when accessing a database. There is a bit more overhead, but it makes the code so much cleaner and less error prone.

Upvotes: 1

Related Questions