0

I am trying to Return a spinner Value inside my BottomSheet Dialog.But It is returing NullPointerException always.Below is my String.XML File

 <string-array name="e_type">
    <item>item1</item>
    <item>item2</item>
</string-array>

This is my bottomsheet_activity.xml file

  <Spinner
    android:id="@+id/spinner"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:entries="@array/e_type" />

And I am trying to Get the value by below code

final BottomSheetDialog dialog3 = new BottomSheetDialog(MainActivity.this);
dialog3.setContentView(R.layout.bottomsheet_activity);

final Spinner spinner=(Spinner) findViewById(R.id.spinner);
final String itemText = (String) spinner.getSelectedItem();

String requesttype=itemText; //Trying to use this variable but returning null

dialog3.show();

Why it is returning null , I have no idea

Mithu
  • 665
  • 1
  • 8
  • 38

3 Answers3

1

Your spinner is null because you are finding it from activity's xml file. Try below code,

final BottomSheetDialog dialog3 = new BottomSheetDialog(MainActivity.this);
View mDialogView = LayoutInflater.from(this).inflate(R.layout.activity_mine, null)
dialog3.setContentView(mDialogView);

final Spinner spinner=(Spinner) mDialogView.findViewById(R.id.spinner);
final String itemText = (String) spinner.getSelectedItem();

String requesttype=itemText; //Trying to use this variable but returning null

dialog3.show();

Hope this will help you!!

Nehal Godhasara
  • 787
  • 3
  • 7
0

I hope this will work for you.

String requesttype;

 @Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    final BottomSheetDialog dialog3 = new BottomSheetDialog(NewActivity.this);
    dialog3.setContentView(R.layout.lay_new);

    final Spinner spinner=(Spinner) dialog3.findViewById(R.id.spinner);

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            requesttype=parent.getItemAtPosition(position).toString();
            Log.e("requesttype",requesttype);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

    dialog3.show();
}
GParekar
  • 1,209
  • 1
  • 8
  • 15
0

You are picking up the reference from

final BottomSheetDialog dialog3 = new BottomSheetDialog(MainActivity.this);
dialog3.setContentView(R.layout.bottomsheet_activity);

so change this-:

final Spinner spinner=(Spinner) findViewById(R.id.spinner);
final String itemText = (String) spinner.getSelectedItem();

to-:

final Spinner spinner=(Spinner) dialog3.findViewById(R.id.spinner);
final String itemText = (String) spinner.getSelectedItem();
Shivam Oberoi
  • 1,447
  • 1
  • 9
  • 18