NullPointerException while changing textView text

2019-07-24 18:55发布

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条回答
\"骚年 ilove
2楼-- · 2019-07-24 19:42

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.

查看更多
登录 后发表回答