按下取消按钮时的Android取消事件

abithluo  于 2023-02-06  发布在  Android
关注(0)|答案(1)|浏览(134)

在我的项目中,当我按下确认按钮时,数据将保存在sqlite上。我想使取消按钮工作取消,而不是插入数据到数据库中。我该怎么做?我正在使用onSaveInstanceState。请帮助我。谢谢。

cancelBtn.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            finish();
        }
    });

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

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

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

private void saveState() 
{
    String name = (String) nameEdit.getText().toString();
    String category = (String) categoryEdit.getText().toString();
    String expired_date = (String) expired_Date_Btn.getText().toString();
    byte[] image = ConvertDrawableToByteArray(mImageView.getDrawable());

    if(mRowId == null)
    {
        long id = mDbHelper.insertItem(category, name, expired_date, image);

        if(id>0)
        {
            mRowId = id;
        }           
    }
    else 
    {
        mDbHelper.updateItem(mRowId, category, name, expired_date, image);
    }   
}
bvhaajcl

bvhaajcl1#

你可以这样做:

AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Choosing time");
        builder.setMessage("Do you want to save the data?");
        builder.setPositiveButton("OK",   new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                saveData(); //Function that saves your the data.
            }
        });
        builder.setNegativeButton("NO",
                new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                finish();// Finish Activity.
            }
        });
        builder.create();
        builder.show();

相关问题