0

I am having a problem with my code that is supposed to display a toast when a button is clicked.

public class MainActivity extends AppCompatActivity {

public Spinner spinner;

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

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


}
public void start(View view) {
    Toast.makeText(this, String.valueOf(spinner.getSelectedItemPosition()) , Toast.LENGTH_LONG).show();
}

}

xml code

<Spinner
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/spinner"
    android:layout_centerVertical="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:entries="@array/jednostki" />

<Button
    android:text="Start"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/spinner"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="71dp"
    android:id="@+id/button"
    android:onClick="start"/>

and of course strings.xml with my array

<resources>
<string name="app_name">02-tempretarureconverter</string>

<string-array name="jednostki">
    <item>Celsjusze</item>
    <item>Farenheity</item>
    <item>Kelwiny</item>
</string-array>
</resources>

I do not know why the Toast message does not display and the program crashes when pressing the button.

Damian
  • 23
  • 1
  • 5

1 Answers1

1

You are not init global variable but using it.

Change this line

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

with

 spinner = (Spinner) findViewById(R.id.spinner);
ugur
  • 3,604
  • 3
  • 26
  • 57