NullPointerException while changing textView text in an AlertDialog

可紊 提交于 2019-12-24 11:49:23

问题


Background:

  • I just want to create a customDialog with a specific layout and add the content.
  • Its a DialogFragment

Code:

TextView text;

@Override
public void onCreate(Bundle savedInstanceState){
 super.onCreate(savedInstanceState);

 text = (TextView)getView().findViewById(R.id.lorem);
 text.setText("Test");
}


@Override
public Dialog onCreateDialog(Bundle savedInstanceState){

 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
 LayoutInflater inflater = getActivity().getLayoutInflater();
 builder.setView(inflater.inflate(R.layout.custom_dialog, null));
 return builder.create();
}

Problem:

  • The Dialog worked, but after I started to add the the lines in "onCreate" I got a NullPointerException Error. I hope someone can help me.

Thanks @Raghunandan for the Answer + explanation and here is the working code:

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState){

     AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
     LayoutInflater inflater = getActivity().getLayoutInflater();
     View view = inflater.inflate(R.layout.custom_dialog_style, null);
     textView = (TextView)view.findViewById(R.id.your_textview);
     textView.setText("Test");
     builder.setView(view);
     return builder.create();
    }

回答1:


At first i thought its a Activity now i see its a DialogFragment.

I am guessing the view belongs to custom_dialog.xml

View view = inflater.inflate(R.layout.custom_dialog, null);
text = (TextView)view.findViewById(R.id.lorem); 
builder.setView(view);

So use the view object to initialize TextView.

text = (TextView)getView().findViewById(R.id.lorem); here getView() returns null.

You are calling setText on null leading to NullPointerException.



来源:https://stackoverflow.com/questions/25363263/nullpointerexception-while-changing-textview-text-in-an-alertdialog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!