Search code examples
androidgettext

Cannot getText From Alert Dialog Android


i have trouble in getText from EditText, i have make all the method that i know but it doesn't work Eventhough i filled the editText the answer allways says Field is required. Here is my code

 private void buildDialog(int animationSource) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    View mView = getLayoutInflater().inflate(R.layout.dialog_activation, null);
    builder.setView(mView);
    AlertDialog dialog = builder.create();
    dialog.getWindow().getAttributes().windowAnimations = animationSource;
    dialog.show();

    Button mLogin = (Button) mView.findViewById(R.id.btnAktivasi);
    mLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AllowingToUpdate();
        }
    });
}

private void AllowingToUpdate() {
    View mView = getLayoutInflater().inflate(R.layout.dialog_activation, null);

    //I want to get Text From mMesin
    EditText mMesin = (EditText) mView.findViewById(R.id.etMesin);
    String NoMesin = mMesin.getText().toString();

    //Toast display always "Field is required" eventhough i have filled the editText

    if(mMesin.getText().toString().equals(""))
    {
        Toast.makeText(this,"Field Is Required....",Toast.LENGTH_SHORT).show();
    }else{
        Toast.makeText(this,"This Is Work....."+NoMesin,Toast.LENGTH_SHORT).show();
    }
}

Solution

  • You are inflating the layout again which will give you a new layout(View) which does not attached to AlertDialog. Keep the things Simple and use the same view which is added to AlertDialog. See the code below you will get the idea .

     private void buildDialog(int animationSource) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View mView = getLayoutInflater().inflate(R.layout.dialog_activation, null);
        builder.setView(mView);
        AlertDialog dialog = builder.create();
        dialog.getWindow().getAttributes().windowAnimations = animationSource;
        dialog.show();
        final EditText mMesin = (EditText) mView.findViewById(R.id.etMesin);
        Button mLogin = (Button) mView.findViewById(R.id.btnAktivasi);
        mLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(mMesin.getText().toString())) {
                    Toast.makeText(ActivityName.this, "Field Is Required....", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(ActivityName.this, "This Is Work....." + mMesin.getText().toString().trim(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    

    Or you can pass mView as a parameter to method AllowingToUpdate. This will also solve it .