Onclick Listener On Button In Dialog Force Closes App
I have two buttons that show in a dialog pop up in my android app. My problem is one of my onclick listeners for one button works, while the other force closes. The error I get is:
Solution 1:
SpinnertasteSpinner= (Spinner)findViewById(R.id.spinn
SpinnerammountSpinner= (Spinner)findViewById(R.id.spinner2);
If the above spinners inside the dialog means change it as,
SpinnertasteSpinner= (Spinner) dialog.findViewById(R.id.spinn
SpinnerammountSpinner= (Spinner) dialog.findViewById(R.id.spinner2);
If you add spinner initialization at below spinner2 is much better instead of inside the button click.
Solution 2:
your error should be on below lines:
SpinnertasteSpinner= (Spinner)findViewById(R.id.spinner1);
SpinnerammountSpinner= (Spinner)findViewById(R.id.spinner2);
you are using dialog spinners so you must have to initialise with dialog like below:
SpinnertasteSpinner= (Spinner)dialog.findViewById(R.id.spinner1);
SpinnerammountSpinner= (Spinner)dialog.findViewById(R.id.spinner2);
Solution 3:
Please change this thing.
StringuserName= prefs.getString("userName", null);
StringuserID= prefs.getString("userID", null);
to
StringuserName= prefs.getString("userName", "");
StringuserID= prefs.getString("userID", "");
If you spinner inside dialog then change.
SpinnertasteSpinner= (Spinner) dialog.findViewById(R.id.spinn
SpinnerammountSpinner= (Spinner) dialog.findViewById(R.id.spinner2);
Solution 4:
AlertDialog
uses builder pattern and has a much easier usage.AlertDialog
dismisses on button press, need not call it explicitly.Always call
equals()
on a non null constant, and pass the other object as parameter.privatevoidAddTaste(){ finalViewv= getLayoutInflater().inflate(R.layout.add_taste_dialog,null); finalSpinners1= (Spinner) v.findViewById(R.id.spinner1); finalSpinners2= (Spinner) v.findViewById(R.id.spinner2); final DialogInterface.OnClickListenerlistener=newDialogInterface.OnClickListener() { @OverridepublicvoidonClick(DialogInterface dialogInterface, int i) { Stringtaste= String.valueOf(s1.getSelectedItem()); Stringamount= String.valueOf(s2.getSelectedItem()); AcceptTaste(taste,amount); } }; newAlertDialog.Builder(this) .setTitle("Add Taste") .setView(v) .setNegativeButton("Cancel",null) .setPositiveButton("Add Taste",listener) .show(); } privatevoidAcceptTaste(String taste, String amount){ inta=0; if("A Hint".equals(amount)){ a= 1; } //--- more stuff--- }
Post a Comment for "Onclick Listener On Button In Dialog Force Closes App"