为什么这段代码给我一个空指针异常?

时间:2018-02-27 23:14:12

标签: java android

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);
    }
}

我知道如果将findviewbyid移动到onclick方法中,代码将运行良好但我想理解为什么它不会以这种方式工作,即使已经调用了setContentView 。

1 个答案:

答案 0 :(得分:2)

也许你放错了结束的大括号。这个应该修复你的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);
    }
}