Question

I am trying to use handle database with insert, update, and delete such as notepad. I'm having problems in canceling data .In normal case which presses the confirm button, it will be saved into sqlite and will be displayed on listview. How can I make cancel event through back key or more button event? I want my Button and back key to cancel data but its keep on saving...

        public static int numTitle = 1;
public static String curDate = "";
private EditText mTitleText;
private EditText mBodyText;
private Long mRowId;
private NotesDbAdapter mDbHelper;
private TextView mDateText;
private boolean isOnBackeyPressed;
public SQLiteDatabase db;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mDbHelper = new NotesDbAdapter(this);
    mDbHelper.open();

    setContentView(R.layout.note_edit);
    setTitle(R.string.edit_note);

    mTitleText = (EditText) findViewById(R.id.etTitle_NE);
    mBodyText = (EditText) findViewById(R.id.etBody_NE);
    mDateText = (TextView) findViewById(R.id.tvDate_NE);

    long msTime = System.currentTimeMillis();
    Date curDateTime = new Date(msTime);

    SimpleDateFormat formatter = new SimpleDateFormat("d'/'M'/'y");
    curDate = formatter.format(curDateTime);

    mDateText.setText("" + curDate);

    Button confirmButton = (Button) findViewById(R.id.bSave_NE);
    Button cancelButton = (Button) findViewById(R.id.bCancel_NE);
    Button deleteButton = (Button) findViewById(R.id.bDelete_NE);

    mRowId = (savedInstanceState == null) ? null
            : (Long) savedInstanceState
                    .getSerializable(NotesDbAdapter.KEY_ROWID);
    if (mRowId == null) {
        Bundle extras = getIntent().getExtras();
        mRowId = extras != null ? extras.getLong(NotesDbAdapter.KEY_ROWID)
                : null;
    }

    populateFields();

    confirmButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            setResult(RESULT_OK);
            Toast.makeText(NoteEdit.this, "Saved", Toast.LENGTH_SHORT)
                    .show();
            finish();
        }

    });
    deleteButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            mDbHelper.deleteNote(mRowId);
            Toast.makeText(NoteEdit.this, "Deleted", Toast.LENGTH_SHORT)
                    .show();
            finish();
        }
    });
    cancelButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            boolean diditwork = true;

            try {
                db.beginTransaction();
                populateFields();
                 db.setTransactionSuccessful();
            } catch (SQLException e) {
                diditwork = false;
            } finally {
                db.endTransaction();
                if (diditwork) {
                    Toast.makeText(NoteEdit.this, "Canceled",
                            Toast.LENGTH_SHORT).show();
                }
            }
        }
    });
}

private void populateFields() {
    if (mRowId != null) {
        Cursor note = mDbHelper.fetchNote(mRowId);
        startManagingCursor(note);
        mTitleText.setText(note.getString(note
                .getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
        mBodyText.setText(note.getString(note
                .getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)));
    }
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    saveState();
    outState.putSerializable(NotesDbAdapter.KEY_ROWID, mRowId);
}

public void onBackPressed() {
    super.onBackPressed();
    isOnBackeyPressed = true;
    finish();
}

@Override
protected void onPause() {
    super.onPause();
    if (!isOnBackeyPressed)
        saveState();
}

@Override
protected void onResume() {
    super.onResume();
    populateFields();
}

private void saveState() {
    String title = mTitleText.getText().toString();
    String body = mBodyText.getText().toString();

    if (mRowId == null) {
        long id = mDbHelper.createNote(title, body, curDate);
        if (id > 0) {
            mRowId = id;
        }
    } else {
        mDbHelper.updateNote(mRowId, title, body, curDate);
    }
}`enter code here`
Was it helpful?

Solution

Here's a short example of using transactions in SQLite (db is a SQLiteDatabase instance in the following):

try {
    db.beginTransaction();
    // your sql stuff
    db.setTransactionSuccessful();
} catch(SQLException e) {
    // do some error handling
} finally {
   db.endTransaction();
}

Notice, its important that whatever method you choose to replace "//your sql stuff" with throws and exception. Use insertOrThrow() or if you need more flexibility SQLiteStatement instances (their .execute methods always throws exceptions on error).

Notice, you do not need to explicititly rollback. If you call db.endTransaction() without .setTransactionSuccessful() it will roll back automatically.

Just remember always to put setTransactionSuccessful after your last SQLException throwing methods :)

You could easy extend this with another catch block, to catch exceptions for network time outs.

Now you can do is a cancel or a back button can act like a exception in this example and automatically the endTransaction will be called which will result in rollBack of your data

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top