Reputation: 1501
I am trying to use handle database with insert, update, and delete such as notepad. I have problem with back key because when I press the back key, I don't want to save any 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 am trying to use onBackPressed, onPause, and onResume. When I press the back key in edit page, onPause() is calling, but I do not want to use saveState() when I pressed back key. How can I make it? Could you give me some feedback? Thanks.
@Override
protected void onPause() {
Toast.makeText(this, "onPause", Toast.LENGTH_SHORT).show();
super.onPause();
saveState();
}
@Override
protected void onResume() {
Toast.makeText(this, "onResume", Toast.LENGTH_SHORT).show();
super.onResume();
Resume_populateFields();
}
@Override
public void onBackPressed() {
Toast.makeText(this, "onBackPressed", Toast.LENGTH_SHORT).show();
super.onBackPressed();
finish();
}
private void saveState() {
String name = (String) nameEdit.getText().toString();
String category = (String) categoryEdit.getText().toString();
String expired_date = (String) expired_Date_Btn.getText().toString();
Bitmap imageBitmap = ((BitmapDrawable) mImageView.getDrawable())
.getBitmap();
ByteArrayOutputStream imageByteStream = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, imageByteStream);
if (mRowId == null) {
long id = mDbHelper.insertItem(category, name, expired_date,
imageByteStream);
if (id > 0) {
mRowId = id;
}
} else {
mDbHelper.updateItem(mRowId, category, name, expired_date,
imageByteStream);
}
}
private void Resume_populateFields() {
if (mRowId != null) {
Cursor data = mDbHelper.fetchItem(mRowId);
startManagingCursor(data);
// load information from sqlite
nameEdit.setText(data.getString(data
.getColumnIndexOrThrow(FridgeDbAdapter.KEY_NAME)));
categoryEdit.setText(data.getString(data
.getColumnIndexOrThrow(FridgeDbAdapter.KEY_CATEGORY)));
expired_Date_Btn.setText(data.getString(data
.getColumnIndexOrThrow(FridgeDbAdapter.KEY_EXPIRED_DATE)));
} else {
// call display date when list is clicked
expired_Date_Btn.setText(new StringBuilder().append(mDay)
.append("/")
// month is 0 based. Then add 1
.append(mMonth + 1).append("/").append(mYear).append(" "));
}
}
Upvotes: 1
Views: 994
Reputation: 31463
Define a boolean flag isOnBackeyPressed; Than:
@Override
public void onBackPressed() {
Toast.makeText(this, "onBackPressed", Toast.LENGTH_SHORT).show();
super.onBackPressed();
isOnBackeyPressed = true;
finish();
}
@Override
protected void onPause() {
Toast.makeText(this, "onPause", Toast.LENGTH_SHORT).show();
super.onPause();
if (!isOnBackKeyPressed)
saveState();
}
If your lifecycle is different, just adopt the idea.
Upvotes: 2