抱歉问一个奇怪的问题,我是java的新手,我将制作一个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();
}
});
}
*/
}
感谢任何建议
答案 0 :(得分:5)
这是因为你没有传递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);
答案 1 :(得分:3)
您已将e1
设置两次,您还需要设置e2
,就像这样
e1 = (EditText)findViewById(R.id.isiharga);
e2 = (EditText)findViewById(R.id.isilaba);