Search code examples
javaandroidmodal-dialogandroid-alertdialog

How can i get the data from view fields which are in custom dialog box in android


I created a custom alert dialog box in the following way

public class CustomDialogBoxForNewEmploy extends Dialog implements android.view.View.OnClickListener {

    Button ok , cancel;
    String name = "" , id = "";

    public CustomDialogBoxForNewEmploy(@NonNull Context context) {
        super(context);
    }

    @Override
    public void onClick(View view) {
        if(view.getId() == R.id.okButton){
            name = ((EditText)findViewById(R.id.employName)).getText().toString();
            id = ((EditText)findViewById(R.id.employId)).getText().toString();
        }else{

        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.custom_dialog_new_employ);

        ok = findViewById(R.id.okButton);
        cancel = findViewById(R.id.cencelButton);
        ok.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }
}

and im calling it when a button get clicked

private void registerNewEmploy(View view){
    CustomDialogBoxForNewEmploy temp = new CustomDialogBoxForNewEmploy(getContext());
    temp.show();

}

but now how can i get the data which is in two text views if i write String x = temp.id; it will be empty

how can i do this?


Solution

  • You need an interface. Create one interface like below

    interface DialogEventListener {
        onSubmit(String id, String name);
    }
    

    then You have to implement this interface in the Activity or fragment from where You are showing this dialog.

    You can pass this interface as an argument in the CustomDialogBoxForNewEmploy. So your new constructor will look like this

    private DialogEventListener listener;
    public CustomDialogBoxForNewEmploy(@NonNull Context context, DialogEventListener listener) {
            super(context);
            this.listener = listener
            }
    

    and from onCLick method of dialog, You can call this interface method