vyn
vyn

Reputation: 25

NullPointerException while changing textView text in an AlertDialog

Background:

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:


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();
    }

Upvotes: 1

Views: 866

Answers (1)

Raghunandan
Raghunandan

Reputation: 133560

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.

Upvotes: 3

Related Questions