Search code examples
androidviewnullpointerexceptionfindviewbyiddialogfragment

Calling findViewById() from DialogFragment subclass gives NullPointerException


In below code, I try to display a basic dialog upon button click. The dialog shows some needs to show some text. I have got it working after i stumpled upon an error, but i still got a question to why that error occurs. In DialogFragmentSubclass.onCreateView() i get a reference to a TextView by calling findViewById(R.id.someIdValue). This gives me NullPointerException. However, getting the reference by calling:

View v = inflate.inflate(someREsourceValue, container, fals);
TextView tv = (TextView) v.findViewById(R.id.someValue);

seems to do the trick. Why does this work, and the other gives me a NullPointerException? (See below for full code)

public class MainActivity extends Activity {
    DownloadImageDialogFragment myDialog;   

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);

        // get reference to buttons
        Button buttonDownloadImage = (Button) findViewById(R.id.downloadImage);
        buttonDownloadImage.setText("Download new Image");

        // upon button click, show a Dialog
        buttonDownloadImage.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                FragmentTransaction ft = getFragmentManager().beginTransaction();

                myDialog = new DownloadImageDialogFragment();
                myDialog.show(ft, null);            
            }
        });

    }

    private class DownloadImageDialogFragment extends DialogFragment {              
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {

                View v = inflater.inflate(R.layout.fragment_dialog, container, false);
                // TextView tv = findViewById(R.id.dialogTextView); // this gives an error
                TextView tv = (TextView) v.findViewById(R.id.dialogTextView); // this works
                tv.setText("This is my dialog");
                return v;
            }
        }
}

And here, the layout file for the dialog:

    <TextView 
        android:id="@+id/dialogTextView"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content" />

</LinearLayout>

Solution

  • When you are calling findViewById(), you are doing so from an inner class of your Activity, which is where this method comes from. Since that view id doesn't exist in your activity's layout, you get null. Your dialog fragment has to inflate its layout (as you have found) before it can get the views defined within it.