javaandroid-studioandroid-edittextandroid-popupwindow

How to use the setText() Method in a PopUp Window In Android Studio?


I have an editText box in my activity in which the user enters his/her phone number and then clicks on a Next button. Now, on clicking on the Button, I have inflated a popup view that shows the user his/her entered number and asks for confirmation.
The problem here is that I am not able to access the number from the EditText to display it in the Popup View. Could anyone tell me how could it be done?

Layout Inflator:

public void onButtonShowPopupWindowClick(View view) {
    // inflate the layout of the popup window

    LayoutInflater inflater = (LayoutInflater)
            getSystemService(LAYOUT_INFLATER_SERVICE);
    @SuppressLint("InflateParams") View popupView = inflater.inflate(R.layout.confirm_number_popup, null);

    ViewGroup root = (ViewGroup) getWindow().getDecorView().getRootView();
    Button btn1 = popupView.findViewById(R.id.btn_edit);

    // create the popup window
    int width = LinearLayout.LayoutParams.WRAP_CONTENT;
    int height = LinearLayout.LayoutParams.WRAP_CONTENT;

    final PopupWindow popupWindow = new PopupWindow(popupView, width, 
 height, false);

    popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
}

When I add this in the inflator, I get a null pointer exception:

    TextView txt_phone_confirm = 
    findViewById(R.id.txt_phone_number_confirm);
    EditText txt_Phone = findViewById(R.id.Phone_Number);
    txt_phone_confirm.setText(txt_Phone.getText().toString());

On doing this, I get:

 java.lang.NullPointerException: Attempt to invoke virtual method 'void 
 android.widget.TextView.setText(java.lang.CharSequence)' on a null 
 object reference

Solution

  • Invoke the find view by id method on the popupView, as this is the view that has your TextView:

     TextView txt_phone_confirm = popupView.findViewById(R.id.txt_phone_number_confirm);
    

    This will get you the text view you just inflated.