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

时间:2011-12-07 16:46:39

标签: android

在我的项目中,当我按下确认按钮时,数据将保存在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);
    }   
}

1 个答案:

答案 0 :(得分:0)

你可以这样做:

        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();