Android: Alert Dialog Box crashing - android

I have an Alert Dialog Box that pops up on the click of a ListView item. The Alert Dialog has a custom layout containing two EditTexts and a TextView. However on calling EditText.getText() on the click of the OK button on the dialog, the application crashes with java.lang.NullPointerException. Please help me in debugging it.
The listview onClickListener code :
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
String cn = cursor.getString(cursor.getColumnIndex("CourseName"));
//Toast.makeText(getApplicationContext(), "Selected: "+cn, Toast.LENGTH_SHORT).show();
LayoutInflater lf = LayoutInflater.from(List_of_Courses.this);
final View DialogView = lf.inflate(R.layout.dialog, null);
final EditText input1 = (EditText) findViewById(R.id.attendanceet);
final EditText input2 = (EditText) findViewById(R.id.totalclasseset);
final AlertDialog.Builder alert = new AlertDialog.Builder(List_of_Courses.this);
alert.setTitle(cn).setView(DialogView).setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int whichbutton) {
Log.v("Test","We're checking");
input1.getText();
input2.getText();
Log.v("Test","We're good");
Log.v("Dialog", input1.getText().toString());
Log.v("Dialog", input2.getText().toString());
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int whichbutton) {
//User clicked cancel so doing nothing.
Log.v("CancelDialog", "User clicked Calcel");
}
});
alert.show();
}
});
The dialog.xml code :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:id="#+id/DialogLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:paddingLeft="25sp"
android:paddingRight="25sp" >
<EditText
android:id="#+id/attendanceet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:layout_weight="1"
android:inputType="number" >
</EditText>
<LinearLayout
android:orientation="vertical"
android:id="#+id/tvLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="6sp" >
<TextView
android:id="#+id/outof"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="/"
android:textSize="20sp"
android:paddingLeft="15sp"
android:paddingRight="15sp"
android:textColor="#FFFFFF" >
</TextView>
</LinearLayout>
<EditText
android:id="#+id/totalclasseset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:layout_weight="1"
android:inputType="number" >
</EditText>
</LinearLayout>
</RelativeLayout>

You should use the dialog object to intialize input1 an input 2.
final View DialogView = lf.inflate(R.layout.dialog, null);
final EditText input1 = (EditText) DialogView.findViewById(R.id.attendanceet);
You can findViewById of the current view hierarchy set to the activity. In your case you inflate a dialog and you current view is the dialog on listview item click. So you should use the dialog object to initialize the views.
You can remove the final modiifier for the below
AlertDialog.Builder alert = new AlertDialog.Builder(List_of_Courses.this);

final EditText input1 = (EditText) findViewById(R.id.attendanceet);
final EditText input2 = (EditText) findViewById(R.id.totalclasseset);
should be
final EditText input1 = (EditText) DialogView.findViewById(R.id.attendanceet);
final EditText input2 = (EditText) DialogView.findViewById(R.id.totalclasseset);

You have to create an AlertDialog before calling show() method. And call show() method on created AlertDialog not on AlertDialogBuilder.
// create alert dialog
AlertDialog alertDialog = alert.create();
Look at this example for reference.

Related

AlertDialog Layout below the buttons

I have my own layout for an AlertDialog, and if I use setPositiveButton everything works. But when i use setItems, my layout is shown below the item buttons.
How can I show my custom layout on top?
Here is my code:
private void selectImage(){
final CharSequence[] items = { TAKE_PICTURE, FROM_GALLERY, CANCLE};
AlertDialog.Builder builder = new AlertDialog.Builder(Add_Object.this);
LayoutInflater inflater = this.getLayoutInflater();
View content = inflater.inflate(R.layout.alert_dialog, null);
builder.setView(content);
((TextView) content.findViewById(R.id.dialogTitle)).setText(R.string.addPictureTitle);
builder.setItems(items, new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals(TAKE_PICTURE)) {
captureImage();
} else if (items[item].equals(FROM_GALLERY)) {
chooseFromGallery();
} else if (items[item].equals(CANCLE)) {
dialog.dismiss();
}
}
});
builder.show();
}
}
And my layout:
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:id="#+id/dialogTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="15dp"
android:layout_marginBottom="15dp"
android:textSize="25sp"
android:textColor="#color/main_color"/>
<View
android:layout_width="match_parent"
android:id="#+id/dialogDivider"
android:layout_below="#id/dialogTitle"
android:layout_height="2dp"
android:background="#color/main_color" />
<TextView
android:id="#+id/dialogText"
android:layout_below="#+id/dialogDivider"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:textSize="18sp"
android:textColor="#color/darkgrey"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Thanks in advance.
You can use builder.setCustomTitle(content) instead of setView(content), but this will add a separator line between your layout and the item buttons...
EDIT:
As an alternative, you can add the list to your custom layout, e.g. with an TextView like this:
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/take_picture"
android:layout_below="#id/dialogText"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:textSize="26sp"
android:onClick="takePicture"/>
and define the takePicture method in your MainActivity:
public void takePicture(View view) {
Log.i("MainActivity", "take picture");
//cancel the dialog
dialog.dismiss();
}
the dialog is saved in a class variable, and initialized in selectImage():
private void selectImage(){
final CharSequence[] items = { "TAKE_PICTURE", "FROM_GALLERY", "CANCLE"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
View title = inflater.inflate(R.layout.alert_dialog, null);
builder.setView(title);
((TextView) title.findViewById(R.id.dialogTitle)).setText("picture title");
((TextView) title.findViewById(R.id.take_picture)).setText(items[0]);
//init dialog
dialog = builder.create();
dialog.show();
}

Can't get CheckedRadioButtonId from within a dialog

This is my first post on Stackoverflow and so far it's been great finding a lot of information here, thank you for that!
I'm trying to have a list with selectable items. when you press the item it may prompt a dialog with 3 radiobuttons. I want to get the ID from the selected radiobutton but for now it always returns the same value. Since i made option 1(Klein) default. pressing a different button and getting that value won't help.
I'm looking forward to tips/tricks/help that you can provide me with(I recently started on android programming, so correct me where I'm wrong!)
// Listview on child click listener
expListView.setOnChildClickListener(new OnChildClickListener() {
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// TODO Auto-generated method stub
Toast.makeText(
getApplicationContext(),
listDataHeader.get(groupPosition)
+ " : "
+ listDataChild.get(
listDataHeader.get(groupPosition)).get(
childPosition), Toast.LENGTH_SHORT)
.show();
if (groupPosition == 4) {
LayoutInflater li = LayoutInflater.from(context);
final View myView = li.inflate(R.layout.dialog, null);
final AlertDialog.Builder Builder = new AlertDialog.Builder(context);
// set layout
Builder.setView(dialog);
// set title
Builder.setTitle("Maak uw keuze");
// set dialog message
Builder
.setCancelable(true)
.setPositiveButton("Bestellen", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
RadioGroup radioGroup1 = (RadioGroup)myView.findViewById(R.id.RadioGroup);
String radiovalue = ((RadioButton)myView.findViewById(radioGroup1.getCheckedRadioButtonId())).getText().toString();
// int selectId =radioGroup1.getCheckedRadioButtonId();
dialog.cancel();
Toast.makeText(MainActivity.this, radiovalue,
Toast.LENGTH_SHORT).show();
}
});
// create alert dialog
AlertDialog alertDialog = Builder.create();
// show it
alertDialog.show();
}
my xml(dialog.xml):
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/RadioGroup"
android:orientation="horizontal"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:checkedButton="#+id/radioButton1"
>
<RadioButton
android:text="Klein"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/radioButton1"
android:layout_alignBaseline="#+id/radioButton"
android:layout_alignBottom="#+id/radioButton"
android:layout_toRightOf="#+id/radioButton"
android:layout_toEndOf="#+id/radioButton"
/>
<RadioButton
android:text="Middel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/radioButton2"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<RadioButton
android:text="Groot"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/radioButton3"
android:layout_alignBaseline="#+id/radioButton2"
android:layout_alignBottom="#+id/radioButton2"
android:layout_toRightOf="#+id/radioButton2"
android:layout_toEndOf="#+id/radioButton2"
android:layout_marginLeft="17dp"
android:layout_marginStart="17dp" />
</RadioGroup>
UPDATED CODE:
.setPositiveButton("Bestellen", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//keep this variables global outside onCreate just like ExpandableListView expListView;
RadioGroup radioGroup1; //this
RadioButton radioButton; // and this too keep global
radioGroup1 = (RadioGroup)myView.findViewById(R.id.RadioGroup);
int something = radioGroup1.getCheckedRadioButtonId();
radioButton = (RadioButton)myView.findViewById(something);
String radioValue = radioButton.getText().toString();
dialog.cancel();
Toast.makeText(MainActivity.this, radioValue,
Toast.LENGTH_SHORT).show();
}
});
Remove the attribute from XML:
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/RadioGroup"
android:orientation="horizontal"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:checkedButton="#+id/radioButton1" //removing this helped me so try to remove and apply the java code.
>
I figured it out!
I had:
LayoutInflater li = LayoutInflater.from(context);
final View myView = li.inflate(R.layout.dialog, null);
final AlertDialog.Builder Builder = new AlertDialog.Builder(context);
// set layout
Builder.setView(dialog);
This Build.setView should refer to my inflater... not the XML itself....
So Builder.setView(myView); Solved the issue!

How can i make my alert dialogue into a custom alert in android

How can i make my alert dialogue into a custom alert in android.please help me to display my dialogue box in a custom alert. my code is pasted here.
the code contains an out put of 10 list view. and when click on item in the list it could be alerted..
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the ListView resource.
mainListView = (ListView) findViewById( R.id.mainListView );
// Create and populate a List of planet names.
final String[] planets = new String[] { "Allu", "Abin", "Bibin", "Aswathy",
"Jibin", "Saran", "Jobin", "Neethu","ammu","Ram"};
final ArrayList<String> planetList = new ArrayList<String>();
planetList.addAll( Arrays.asList(planets) );
// Create ArrayAdapter using the planet list.
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, planetList);
/*// Add more planets. If you passed a String[] instead of a List<String>
// into the ArrayAdapter constructor, you must not add more items.
// Otherwise an exception will occur.
listAdapter.add( "Ceres" );
listAdapter.add( "Pluto" );
listAdapter.add( "Haumea" );
listAdapter.add( "Makemake" );
listAdapter.add( "Eris" );*/
// Set the ArrayAdapter as the ListView's adapter.
mainListView.setAdapter( listAdapter );
mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Alert Dialog With EditText"); //Set Alert dialog title here
alert.setMessage("Edit Your Name Here"); //Message here
final EditText input = new EditText(context);
input.setText((String)planetList.get(position));
alert.setView(input);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String srt = input.getEditableText().toString();
Toast.makeText(context,srt, Toast.LENGTH_LONG).show();
planetList.set(position, srt);
listAdapter.notifyDataSetChanged();
}
});
alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
}); //End of alert.setNegativeButton
AlertDialog alertDialog = alert.create();
alertDialog.show();
}
});
}
}
That's a simple way to make a popup dialog with a custom xml layout, It will surely work:
Make an xml file for your dialog. Set android:layout_width="wrap_content" and android:layout_height="wrap_content" or any other size. You can also set a background for your layout.
For example this is an xml layout for a popup window:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/popup_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#color/black" >
<TextView
android:id="#+id/title_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="15dp"
android:paddingBottom="5dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:text="title"
android:textColor="#color/white"
android:textAppearance="?android:attr/textAppearanceLarge" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal">
<TextView
android:id="#+id/details_tv"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:paddingTop="40dp"
android:paddingBottom="20dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="Enter your name here:"
android:textColor="#color/white"
android:layout_weight="1"
android:layout_gravity="center"/>
<EditText
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="#color/white"
android:layout_gravity="center"
android:layout_marginRight="8dp"
android:inputType="textPersonName"
android:text="Name"
android:ems="10"
android:id="#+id/editText"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dp"
style="?android:attr/buttonBarStyle" >
<Button
android:id="#+id/cancel_btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Cancel"
android:onClick="cancel"
android:textColor="#color/white"
style="?android:attr/buttonStyle" />
<Button
android:id="#+id/exit_btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="OK"
android:onClick="ok"
android:textColor="#color/white"
style="?android:attr/buttonStyle" />
</LinearLayout>
</LinearLayout>
And that's how you show the popup:
private void showPopup(final Activity context) {
LinearLayout viewGroup = (LinearLayout) context.findViewById(R.id.popup_layout);
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layoutPopup = layoutInflater.inflate(R.layout.layout_popup, viewGroup);
popup = new PopupWindow(context);
popup.setContentView(layoutPopup);
popup.setWidth(LayoutParams.WRAP_CONTENT);
popup.setHeight(LayoutParams.WRAP_CONTENT);
popup.setFocusable(true);
popup.showAtLocation(layoutPopup, Gravity.CENTER, 0, 0);
}
You can use simple onClick methods for buttons in your popup dialog:
public void cancel(View v){
Toast.makeText(getApplicationContext(), "Canceled",
Toast.LENGTH_LONG).show();
popup.dismiss();
}
public void ok(View v){
Toast.makeText(getApplicationContext(), "Done",
Toast.LENGTH_LONG).show();
popup.dismiss();
}
You can also read this for another way of creating custom dialogs.
public class MyDialog extends DialogFragment {
public static MyDialog getInstance() {
MyDialog dialog = new MyDialog ();
Bundle bundle = new Bundle();
bundle.putInt("your key", "save something");
dialog.setArguments(bundle);
return dialog;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder vBuilder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = LayoutInflater.from(getActivity());
View view = inflater.inflate(R.layout."your custom layout", null);
yourEditText = (TextView) view.findViewById(R.id."your edit text id");
Bundle bundle = getArguments();
if(bundle!=null){
... do something
}
vBuilder.setView(view);
return vBuilder.create();
}
}
To open this dialog
MyDialog.getInstance().show(getFragmentManager(), "your TAG");
Why can't you use dialog?
dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog);//create an xml and use it.
dialog.setCancelable(true);
passwordEmail = (EditText) dialog
.findViewById(R.id.dialog_txt_name);
dialog.show();
Instead of this :
final EditText input = new EditText(context);
input.setText((String)planetList.get(position));
alert.setView(input);
Write this :
LayoutInflater inflater = LayoutInflater.from(getActivity());
View view = inflater.inflate(R.layout."your custom layout", null);
alert.setView(view);

insert a new TextView in a dialog box after pressing on a button in the dialog box

i have a custom dialog box, it has a textview an edittext and 2 buttons. i'm trying to create a new textview that containes the text of the edittext everytime the user presses on the 'add' button,and locate it beneath the buttons. how can i do that? here's what i tried:
ingDlgBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//showDialog(INGS_DIALOG);
final Dialog customIngsDlg = new Dialog(context);
customIngsDlg.setContentView(R.layout.custom_ings_dialog);
customIngsDlg.setTitle("Ingredients");
TextView ingsDlgTitle = (TextView)findViewById(R.id.ingsDialogTitleTv);
final EditText ingsEt = (EditText)customIngsDlg.findViewById(R.id.ingsDialogEt);
final Button ingsAddBtn = (Button)customIngsDlg.findViewById(R.id.ingsAddButton);
final Button ingsFinishBtn = (Button)findViewById(R.id.ingsFinishButton);
ingsAddBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// ArrayList<String> ingsTmp = new ArrayList<String>();
String ingredient = ingsEt.getText().toString();
ingredients.add(ingredient);
ingsEt.setText("");
TextView ingItemTv = new TextView(customIngsDlg.getContext());
ingItemTv.setText(ingredient);
RelativeLayout layout = new RelativeLayout(OwnRecipeAdding.this);
RelativeLayout.LayoutParams parms = new RelativeLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
parms.addRule(RelativeLayout.BELOW,ingsEt.getId());
layout.setLayoutParams(parms);
customIngsDlg.addContentView(ingItemTv,parms);
}
});
// ingsFinishBtn.setOnClickListener(new View.OnClickListener() {
//
// #Override
// public void onClick(View v) {
//
// customIngsDlg.dismiss();
// }
// });
customIngsDlg.show();
}
});
I would suggest adding the text view to your custom layout in the .xml file and then add text to that when the add button is pressed.
This needs a bit of styling, but it's functional. You'll likely need a scroll view in there when the list becomes too long.
Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/dialog_fragment_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/dialog_textview_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:text="Add Ingredients" />
<EditText
android:id="#+id/dialog_edittext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="left" />
<LinearLayout
android:id="#+id/button_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="#+id/button_add"
style="?android:attr/buttonBarButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add" />
<Button
android:id="#+id/button_finish"
style="?android:attr/buttonBarButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Finish" />
</LinearLayout>
<TextView
android:id="#+id/dialog_textview_2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:text="" />
</LinearLayout>
DialogFragment class:
public class TestDialogFragment extends DialogFragment {
private Button buttonAdd;
private Button buttonFinish;
private TextView addTextView;
private EditText editText;
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialoglayout = inflater.inflate(R.layout.dialog_fragment, null);
buttonAdd = (Button)dialoglayout.findViewById(R.id.button_add);
buttonFinish = (Button)dialoglayout.findViewById(R.id.button_finish);
editText = (EditText)dialoglayout.findViewById(R.id.dialog_edittext);
addTextView = (TextView)dialoglayout.findViewById(R.id.dialog_textview_2);
buttonAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String text = addTextView.getText().toString();
text = text + "\n" + editText.getText().toString();
addTextView.setText(text);
editText.setText("");
}
});
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(dialoglayout)
.setTitle("Ingredients")
.setCancelable(false)
.setInverseBackgroundForced(true);
AlertDialog dialog = builder.create();
return dialog;
}
}

NullpointerException on an inflated View

I have an inflated layout inside an AlertDialog. When I refer to one of its view I get a NullpointerException.
The view with id spinner lies inside the layout dialog_with_spinner.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout_root"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/linear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="20dp">
<TextView
android:id="#+id/info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:text="#string/info_title" />
<Spinner
android:id="#+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:entries="#array/entries"
android:saveEnabled="true"/>
</LinearLayout>
<CheckBox
android:id="#+id/someId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/someString"/>
</LinearLayout>
Code:
AlertDialog.Builder builder = new AlertDialog.Builder(boxThemeContextWrapper);
LayoutInflater inflater = getLayoutInflater();
builder.setView(inflater.inflate(R.layout.dialog_with_spinner, null))
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
final Spinner sp = (Spinner) findViewById(R.id.spinner);
int p = sp.getSelectedItemPosition(); // this gets the **NullPointerException**
String[] entryValues = getResources().getStringArray(R.array.entry_values);
final String entry = entryValues[p];
useMyEntryMethod(entry);
}
})
.setNegativeButton(R.string.dialogs_negative, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//
}
});
builder.show();
How do I fix this? thanks.
Replace
final Spinner sp = (Spinner) findViewById(R.id.spinner);
with
final Spinner sp = (Spinner) dialog.findViewById(R.id.spinner);
Access Spinner with dialog's reference for findViewById().
Update:
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_with_spinner, null);
setView(view)
And then Access Spinner using view, Like,
final Spinner sp = (Spinner) view.findViewById(R.id.spinner);

Categories

Resources