2014-03-19 52 views
-1

我點擊添加按鈕時收到空指針異常。這是行號39也就是在這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

寫這個,而不是 「C」,並檢查它。或者Calci.this。 –

+0

爲什麼在大寫字母中發佈您的所有問題? –

+0

給過答案幫助過嗎? –

回答

1

你沒有初始化Context對象c。現在,初始化c如下...

Context c = this; 

或如下面...

Context c = Calci.this; 

如果你不想使用Context對象c然後如下初始化AlertDialog.Builder ..

AlertDialog.Builder a1 = new AlertDialog.Builder(Calci.this); 
+4

也許上下文c = Calci.this;會打擊。不是嗎? – marson

0

使用Activityname.this insted爲「c」。

+0

這必須是評論。不接受爲答覆。 – Piyush

0

變線39:

AlertDialog.Builder a1 = new AlertDialog.Builder(getApplicationContext());