Search code examples
androiddialogandroid-alertdialog

how to send data from activity to AlertDialog to display them


Code to create builder:

    builder = new AlertDialog.Builder(this);
    builder.setPositiveButton("connect",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int     id) {
                    devices.get(currentPos).setConnected(true);
                }
            });
    builder.setNegativeButton("dismiss",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // User cancelled the dialog
                }
            });
    builder.setView(getLayoutInflater().inflate(
            (R.layout.activity_device_details), null));
    builder.setTitle("more information");

Notice the: builder.setView() to R.layout.activity_device_details which have some TextViews that I want to fill when I create the dialog with this code:

    BPDevice dev = new BPDevice();
    dev = devices.get(position);

    AlertDialog dialog = builder.create();

    ((TextView) dialog.findViewById(R.id.name)).setText(dev.getName());

    dialog.show();

I get a nullpointerException because of this line: ((TextView) dialog.findViewById(R.id.name)).setText(dev.getName());

¿How can I fill the TextViews properly?


Solution

  • First inflate root layout that has you text views. Then your child views. Then set data and set root as view of alert dialog.

    View root = getLayoutInflater().inflate(
            (R.layout.activity_device_details),null);
     
    TextView textView =(TextView)root.findViewById(R.id.your_textview_layout_name);
    textView.setText("Your data");
    builder.setView(root);