致命异常:主要在android中

时间:2013-09-24 08:18:48

标签: android nullpointerexception

我是Android编程领域的初学者。 我只是想开发一个示例应用程序。 这是项目:

public class CalcActivity extends Activity implements OnClickListener{

EditText input = (EditText) findViewById(R.id.input);
Button one = (Button) findViewById(R.id.button1);
TextView out = (TextView) findViewById(R.id.output);
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_calc);
    //one.setOnClickListener(this);
}
public void onClick(View v){

  input.setText("HI");
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.calc, menu);
    return true;
}

}

2 个答案:

答案 0 :(得分:0)

试试这个

public class CalcActivity extends Activity implements OnClickListener {

EditText input ;
Button one ;
TextView out;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_calc);
    input = (EditText) findViewById(R.id.input);
    one = (Button) findViewById(R.id.button1);
    one.setOnClickListener(this);
    out = (TextView) findViewById(R.id.output);
    // one.setOnClickListener(this);
}

public void onClick(View v) {
    switch (v.getId()) {
    case R.id.button1:
        input.setText("HI");
        Log.d("button clicked", "buttom");
        break;
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.calc, menu);
    return true;
}

}

答案 1 :(得分:0)

你没有初始化Oncreate()内部的视图,因此你正在强行关闭 所以在onCreate中初始化你的视图就像这样

EditText input;
Button one ;
TextView out;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_calc);
    input= (EditText) findViewById(R.id.input);
    one = (Button) findViewById(R.id.button1);
    out = (TextView) findViewById(R.id.output);

}