2017-09-21 40 views
-4

我正在製作一個像計算器一樣的應用程序..我的計算器android應用程序有什麼問題?

這是我的代碼片段。

EditText etfirst,etsecond; 
Button btnadd; 

etfirst = (EditText)findViewById(R.id.etfirst); 
etsecond = (EditText)findViewById(R.id.etsecond); 
btnadd = (Button)findViewById(R.id.btnadd); 

btnadd.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      int first,second,result; 
      first= Integer.valueOf(etfirst.getText().toString()); 

      second = Integer.valueOf(etsecond.getText().toString()); 
      result = first + second; 
      tvresult.setText("Result: " + result); } 
}); 

我的問題是,當我從EditText上獲得整數值的TextView它不工作..

我也試過的Integer.parseInt(String的形式);但它也沒有幫助..

請指導我如何使我的正常

+0

什麼是錯誤? – user3808887

+0

定義「不工作」。 – John3136

+0

致命例外:main 進程:com.example.ajdeveloper.myapplication,PID:32227 java.lang.NullPointerException:嘗試調用虛擬方法'void android.widget.TextView.setText(java.lang.CharSequence)'on a null對象引用 at com.example.ajdeveloper.myapplication.MainActivity $ 1.onClick(MainActivity.java:40) –

回答

0

使用性能inputType:number或者也可以的inputTypenumberDecimal值。

因爲默認情況下edittext將接受所有的字符/數字等等,但是隻能轉換爲整數才能處理數字值。

+0

Thanx for Reply Bro ..我很感激..但它也不起作用 –

0

改變這一行

tvresult.setText("Result: " + result); 

tvresult.setText("Result: " + String.valueOf(result)); 

和跟它NullPointerException異常與XML對象綁定變量tvresult

+0

沒有工作...錯誤在40行保持不變... 40行:秒= Integer.valueOf(etsecond.getText()的ToString()); –

+0

你可以嘗試'Integer.parseInt(etsecond.getText()。toString())'行40 – mismanc

+0

並檢查你的xml文件'etsecond'沒有約束力我猜。因此,它拋出'NullPointerException' – mismanc