Skip to content Skip to sidebar Skip to footer

How To Pass A Variable Or Object To Dialog In Android

I have a custom dialog with one editText view and two buttons ok and cancel. I have a custom list view displaying some rows of data fetched from database. When the user clicks on t

Solution 1:

Instead of using showDialog(CUSTOM_DIALOG_ID) use you can create a your own method with argument and in that you can use AlertDialog to display your view that contains textview and buttons.

i)   private AlertDialog alert;   should be declared in class scope above oncreate().

ii) Instead of showDialog(CUSTOM_DIALOG_ID) use createDialog(cmt)

iii) private void createDialog(Comment cmt){
        AlertDialog.Builder dialog = new AlertDialog.Builder(TestDatabaseActivity.this);
        View view = _inflater.inflate(R.layout.comment_edit_dialog,null);
        dialog.setTitle("Edit");

        dialog_editComment = (TextView)view .findViewById(R.id.editComment);
        dialog_txtEditComment = (EditText)dialog.findViewById(R.id.txtComment);
        dialog_btnOk = (Button)view .findViewById(R.id.btnOk);
        dialog_btnCancel = (Button)view .findViewById(R.id.btnCancel);

        dialog_btnOk.setOnClickListener(customDialog_UpdateOnClickListener);
        dialog_btnCancel.setOnClickListener(customDialog_DismissOnClickListener);
        dialog.setView(view);
        //dialog.show();
        alert = dialog.create();
        alert.show();
    }

iV) also instead of dismissDialog(CUSTOM_DIALOG_ID) use alert.dismiss();


Solution 2:

Also another solution to your problem is change the scope of cmt.  

i.e., Above onCreate() declare 

private Comment cmt; 

now it can be access the TestDatabaseActivity. in your code make a minor change and try 

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    CommentAdapter adapter= (CommentAdapter) getListAdapter();
    cmt = adapter.mListComment.get(position);
    System.out.println(cmt.getId()+cmt.getComment());

            //cmt is the object which i want to pass to my dialog
    showDialog(CUSTOM_DIALOG_ID);
}

also declare private Comment cmt = null; above oncreate() and then in onCreateDialog() you can access 

System.out.println(cmt.getId()+cmt.getComment());

Try .....

Post a Comment for "How To Pass A Variable Or Object To Dialog In Android"