0

spinner error when dialog show . my position dialog in adapter

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.widget.Spinner.getSelectedItem()' on a null object reference

private void stopDialog(final MyViewHolder holder, int position){

    android.app.AlertDialog.Builder dialog = new android.app.AlertDialog.Builder(context);
    LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
    View dialogView = inflater.inflate(R.layout.dialog_stop, null);
    dialog.setView(dialogView);
    dialog.setCancelable(false);

    final Button dialog_button_positive = (Button) dialogView.findViewById(R.id.dialog_button_positive);
    final Button dialog_button_negative = (Button) dialogView.findViewById(R.id.dialog_button_negative);
    final Spinner statusstop1 = (Spinner) dialogView.findViewById(R.id.statusstop);
    final String valuestatustop = statusstop1.getSelectedItem().toString();




    final android.app.AlertDialog alertDialog = dialog.create();
    alertDialog.show();

    dialog_button_negative.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            holder.switch_start.setChecked(true);
            alertDialog.dismiss();

        }
    });

    dialog_button_positive.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            Toast.makeText(context,
                    valuestatustop,
                    Toast.LENGTH_SHORT).show();

            alertDialog.dismiss();

        }
    });




}

3 Answers3

1

Check you xml file because your statusstop1 is null. Make sure in your xml statusstop id available in spinner.

Mitesh Vanaliya
  • 2,491
  • 24
  • 39
0

I assume statusstop1 is null, and that is causing the NPE. I think this is caused because you are trying to access a View that is in a fragment that you just 'inflated'. You should not do that because inflation is not synchronous. Putting a thread.sleep before accessing the R.id.statusstop should solve the problem if my theory is correct.

If that is the case, you should put the code that need to access the properties of the fragment inside the fragment class, and use other means of communication between activity and fragement, or fragment to fragment: https://developer.android.com/training/basics/fragments/communicating

David Raluy
  • 184
  • 5
0

Make sure that the Spinner object has some items listed in it before you call the getSelectedItem() method.

Some cases of Null pointer Exception could also arise just from the fact that the Spinner Object has nothing to show and the getSelectedItem() method is trying to fetch a list of items which hasn't been listed yet.

Vikas
  • 23
  • 1
  • 8