当我点击添加按钮时,我收到空指针异常。它在AlertDialog.Builder a1 = new AlertDialog.Builder(c)
行
package com.example.calculator;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Calci extends Activity {
TextView t1;
EditText e1, e2;
Button add, sub, mul, div;
Context c;
String b, a;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calci);
e1 = (EditText) findViewById(R.id.EditText01);
e2 = (EditText) findViewById(R.id.EditText02);
add = (Button) findViewById(R.id.add);
sub = (Button) findViewById(R.id.sub);
mul = (Button) findViewById(R.id.mul);
div = (Button) findViewById(R.id.div);
t1 = (TextView) findViewById(R.id.textView1);
a = e1.getText().toString();
b = e2.getText().toString();
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if (a.matches("") || b.matches("")){
AlertDialog.Builder a1 = new AlertDialog.Builder(c);
// Setting Dialog Title
a1.setTitle("Alert Dialog");
// Setting Dialog Message
a1.setMessage("PLEASE ENTER SOMETHING");
a1.setPositiveButton("yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int button1) {
// if this button is clicked, close
// current activity
dialog.cancel();
}
});
// Showing Alert Message
AlertDialog alertDialog = a1.create();
a1.show();
}
int result = Integer.parseInt(a) + Integer.parseInt(b);
t1.setText(Integer.toString(result));
}
});
}
}
答案 0 :(得分:1)
您没有初始化Context
对象c
。现在,初始化c
如下...
Context c = this;
或者,如下所示......
Context c = Calci.this;
如果您不想使用Context
对象c
,请按以下方式初始化AlertDialog.Builder
...
AlertDialog.Builder a1 = new AlertDialog.Builder(Calci.this);
答案 1 :(得分:0)
使用活动名称。而不是“c”。
答案 2 :(得分:0)
将第39行更改为:
AlertDialog.Builder a1 = new AlertDialog.Builder(getApplicationContext());