2012-11-26 119 views
0

这是一个在android中的简单应用程序。它在执行时显示nullpointerexception。 我无法从edittext获得值。在这里,我只想从edittext获得值。 但它显示nullpointerexception ..如何解决android中的NullPointer异常?

如何解决这个问题?

public class Calci extends Activity { 
    Button add; 
    String str1; 
    String str2; 
    EditText txt1; 
    EditText txt2; 
    TextView tv; 

    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_calci); 

     add=(Button) findViewById(R.id.button1); 
     txt1=(EditText) findViewById(R.id.editText1); 
     str1=txt1.getText().toString(); 
     txt2=(EditText) findViewById(R.id.editText2); 
     str2=txt2.getText().toString(); 
     tv=(TextView) findViewById(R.id.textView4); 

     addition(); 

     add.setOnClickListener(new View.OnClickListener() { 

      public void onClick(View v) { 
       addition(); 
      } 
     }); 
    } 


    private void addition(){ 
     int res=0; 
     res=Integer.parseInt(str1)+Integer.parseInt(str2); 
     tv.setText(String.valueOf(res)); 
    } 

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

请出示您的logcat –

+0

找到它允许您从logcat的错误的行。 –

+0

它没有显示logcat。显示一个消息框,运行该应用程序。 – AndRaGhu

回答

2

确保您在XML为editText1editText2设置的默认值,或者如果您要访问的值由用户输入,然后chnage你的代码,并删除除( )setOnClickListener前:

 // addition(); comment this line 
     add.setOnClickListener(new View.OnClickListener() 
     { 

      public void onClick(View v) 
      { 
        str1=txt1.getText().toString(); 
        str2=txt2.getText().toString(); 
        addition(); 

      } 
     }); 
2

刚刚从onCreate()删除addition();。因为我怀疑它第一次叫你的EditTexts是空的。

此外,当你调用addition()方法,你必须从你的两个EditTexts文本。

而且你的方法addition()类似,

private void addition() 
{ 

    int res=0; 
    str1=txt1.getText().toString(); 
    str2=txt2.getText().toString(); 
    res=Integer.parseInt(str1)+Integer.parseInt(str2); 
    tv.setText(String.valueOf(res)); 
} 
+0

然后我应该声明方法? – AndRaGhu

+0

只在Button的'onClick()'中。或者如果你想放入你的'onCreate()',那么在Layout XML文件的EditText属性中放置一些默认值。在调用'additon()'之前或给'str1'和'str2'一些默认值。 – user370305

0

你不叫除了()这个方法在这里:

 str2=txt2.getText().toString(); 
     tv=(TextView) findViewById(R.id.textView4); 

     //addition(); 


     add.setOnClickListener(new View.OnClickListener() 
1

只需更换你的OnCreate()的additiion()方法,改变方法,如下面

private void addition() 
    { 
     str1= str1==null?"0":str1;// do like this, so that if str1 returns null then it will be replaced by 0 
     str2= str2==null?"0":str2; 
     int res=0; 
     res=Integer.parseInt(str1)+Integer.parseInt(str2); 
     tv.setText(String.valueOf(res)); 
    } 
+0

嗨,我需要解释一下这个pblm。并在此之前,感谢您的帮助.. – AndRaGhu

+0

当你的字符串将变为null时,它会自动帮助你通过使用此代码获取空指针异常 –