Reputation: 187
I'm having some trouble with NullPointerException showing up when I click on the positive button of my DialogFragment
. I set a layout mainly composed of EditText and I am using their contents in my app. The problems appears when the app tries to retrieve the contents of the EditText
In my MainActivity
, I set a Listener on a Button
which calls the DialogFragment
with the show()
method.
Here is the code snippet describing my DialogFragment
:
private class PersonalInfoDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.personalinformation)
.setView(inflater.inflate(R.layout.personalinformation_dialog, null))
.setPositiveButton(R.string.edit, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
EditText name_options = (EditText) findViewById(R.id.name_options);
//This line makes the app crash:
String text = name_options.getText().toString();
//doing some job...
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
Why does that exception happens?
Upvotes: 1
Views: 570
Reputation: 132982
Use View
object which you are passing to setView
for accessing EditText
from layout of Dialog
. do it as :
final View view=inflater.inflate(R.layout.personalinformation_dialog, null);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.personalinformation)
.setView(view)
....
Get EditText for Dialog in onClick method:
EditText name_options = (EditText)view. findViewById(R.id.name_options);
Upvotes: 1
Reputation: 12365
I think that you should use this:
EditText name_options = (EditText) getDialog().findViewById(R.id.name_options);
Upvotes: 2
Reputation: 12358
Change
EditText name_options = (EditText)findViewById(R.id.name_options);
to
EditText name_options = (EditText)getactivity().findViewById(R.id.name_options);
Upvotes: 0
Reputation: 870
EditText name_options = (EditText) findViewById(R.id.name_options);
this probably returns null.
Try using getActivity().findViewById(R.id.name_options)
or passing the context/view which contains the name_options
view
Upvotes: 0
Reputation: 412
If line
String text = name_options.getText().toString();
causes NullPointerException then it is possible that name_options
is null, so probaly there is no EditText with name_options
id in your layout.
Upvotes: 0
Reputation: 410
Bro.. when you initialize your xml controller please use this
yourview.findViewById(R.id.name_options);
Upvotes: 3