我正在尝试使用带有插入、更新和删除功能的句柄数据库,例如记事本。我有返回键的问题,因为当我按下返回键时,我不想保存任何数据。在正常情况下按下确认按钮,它将被保存到 sqlite 并显示在 listview 上。如何通过返回键或更多按钮事件进行取消事件?我正在尝试使用 onBackPressed、onPause 和 onResume。当我在编辑页面中按下返回键时,onPause() 正在调用,但是当我按下返回键时我不想使用 saveState()。我怎样才能做到?你能给我一些反馈吗?谢谢。
@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(" "));
}
}