基于微调器值启动新活动会导致意外停止

时间:2014-03-30 02:21:51

标签: android spinner buttonclick

没有错误,但应用无法启动

public class MainActivity extends Activity {

Button button1;

@Override
protected void onCreate(Bundle b) {
    super.onCreate(b);
    setContentView(R.layout.activity_main);


Spinner spinner = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.Class, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);

Spinner nspinner = (Spinner) findViewById(R.id.spinner2);
ArrayAdapter<CharSequence> nadapter = ArrayAdapter.createFromResource(this,R.array.hour, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
nspinner.setAdapter(nadapter);

final String text = spinner.getSelectedItem().toString();
final String ntext = nspinner.getSelectedItem().toString();

button1.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        if (text.equals("IT6")){
            Intent myIntent = new Intent(v.getContext(),
                    One.class);
            startActivity(myIntent);
        } else if (text.equals("IT8")){
        Intent myIntent = new Intent(v.getContext(),
                Two.class);
        startActivity(myIntent);
        } 
    }

});

1 个答案:

答案 0 :(得分:1)

如果它崩溃,那么你的logcat中总会有你应该发布的输出。但是在这里,您似乎永远不会初始化button1,因此在尝试设置NPE时会得到Listener。你需要setContentView()之后的东西

button1 = (Button) findViewById(R.id.someId);