Search code examples
androidandroid-dialogfragment

Dialog Fragment(custom layout) is not working when displaying TextView


I have read some of the posts here but they dont seem to fix my problem.

enter image description here

MainActivity.java

public class MainActivity extends AppCompatActivity {

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

    Button button=(Button)findViewById(R.id.button2);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            dialog my_alert=new dialog();
            my_alert.show(getFragmentManager(),"");
        }
    });

}
}

dialog.java

public class dialog extends DialogFragment {

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder build=new AlertDialog.Builder(getActivity());
    LayoutInflater inflater;
    View v;
    inflater=getActivity().getLayoutInflater();
    v=inflater.inflate(R.layout.dialog_layout,null); 
    build.setView(v);
    return build.create();

}

}

The above coding is working before I add textview.

However, what I want to do is to display textview in the custom layout. If I add the following coding below build.setView(v) , it exits.

build.setView(v)
TextView tv=(TextView)getActivity().findViewById(R.id.textView);
tv.setText("my text here");
return build.create();

Logcat error

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

Solution

  • Do this in onCreateDialog()

    View v;
    inflater=getActivity().getLayoutInflater();
    v=inflater.inflate(R.layout.dialog_layout,null); 
    TextView tv=(TextView)v.findViewById(R.id.textView);
    tv.setText("my text here");**