Android應用計數c=a+b,一直報nullpointerexception。
代碼:
public class Kreasi extends Activity {
// Inisialisasi
private EditText e1;
private EditText e2;
private Spinner s1;
private Button b1;
private Button b2;
private TextView t1;
private TextView t2;
private TextView t3;
private TextView t4;
private TextView t5;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.kreasi);
// INISIALISASI VARIABEL
e1 = (EditText)findViewById(R.id.isiharga);
e1 = (EditText)findViewById(R.id.isilaba);
s1 = (Spinner)findViewById(R.id.spin);
b1 = (Button)findViewById(R.id.process);
b2 = (Button)findViewById(R.id.reset);
t1 = (TextView)findViewById(R.id.hMax);
t2 = (TextView)findViewById(R.id.angPokok);
t3 = (TextView)findViewById(R.id.angSewa);
t4 = (TextView)findViewById(R.id.angTotal);
b1.setOnClickListener(new OnClickListener(){
int a,b;
@Override
public void onClick(View v) {
hideSoftKeyboard(b1);
String aa,bb;
aa = e1.getText().toString();
bb = e2.getText().toString();
a = Integer.valueOf(aa);
b = Integer.valueOf(bb);
int c = (int) (a + b);
t1.setText(Integer.toString(c));
}
});
}
// Menyembunyikan Keyboard
public void hideSoftKeyboard(Button btn) {
btn.setInputType(0);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(btn.getWindowToken(), 0);
}
/*
// Fungsi saat tombol process ditekan
public void tombolprocess(){
b1.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
hideSoftKeyboard(b1);
aa = e1.getText().toString();
bb = e2.getText().toString();
Toast.makeText(getBaseContext(),"a="+aa +" b=" +bb,Toast.LENGTH_SHORT).show();
}
});
}
*/
}
因為你沒給e2賦值:
將:
e1 = (EditText)findViewById(R.id.isiharga);
e1 = (EditText)findViewById(R.id.isilaba);
改為:
e1 = (EditText)findViewById(R.id.isiharga);
e2 = (EditText)findViewById(R.id.isilaba);