0
public class FindBeerActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_beer);
    }
    Spinner color = (Spinner) findViewById(R.id.color);
    TextView brands = (TextView) findViewById(R.id.brands);


    public void onClickFindBeer(View view) {

        //Get the selected item in the spinner
        String beerType = String.valueOf(color.getSelectedItem());

        //Display the selected item
        brands.setText(beerType);
    }
}

I know if I move the findviewbyid's into the onclick method, the code will run fine but i would like to understand why it wont work this way even though the setContentView has already been called.

Sunil
  • 3,404
  • 10
  • 23
  • 31
  • 3
    You views haven't yet been created at that point because `setContentView` has NOT been called. Just because you put code lower in the file doesn't mean it executes later. Seems like you should be doing java tutorials before moving to Android ones. – takendarkk Feb 27 '18 at 23:20
  • Ok, thanks alot. I think i better go back and learn java properly – James Idowu Feb 28 '18 at 12:29

1 Answers1

2

Perhaps you misplaced the closing curly-brace. This one should fix your NPE.

public class FindBeerActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_beer);
        Spinner color = (Spinner) findViewById(R.id.color);
        TextView brands = (TextView) findViewById(R.id.brands);
    }

    public void onClickFindBeer(View view) {
        //Get the selected item in the spinner
        String beerType = String.valueOf(color.getSelectedItem());
        //Display the selected item
        brands.setText(beerType);
    }
}
Wei
  • 1,028
  • 8
  • 27