Search code examples
androidandroid-activitybigdecimal

App crashes because of BigDecimal


I simply have two editText views. One is in the main activity and one is in an alert dialog. The one in the main activity contains a string of numbers (i.e. 0.00) and my goal is to add whatever the user inputs from the second editText in the alert dialog to the number in the main activity.

I am trying to use BigDecimals to do the addition and here is my code in a onClickListnener

   private BigDecimal user_input;
   private BigDecimal original;
   private BigDecimal sum;
   protected void onCreate(Bundle savedInstanceState){
   .
   .
   .
   .
                 //here is the problem
                 user_input=new BigDecimal( editText_in_alert.getText().toString());
                 original  =new BigDecimal( editText_in_main_activity.getText().toString());
                 sum=user_input.add(original); 

Is that how we are supposed to convert a string into a BigDecimal and add them up together?

My app crashes when I click on a button but it works fine when I remove the BigDecimal operations...

here is the log :

      java.lang.NumberFormatException: Invalid long: " 000 "
        at java.lang.Long.invalidLong(Long.java:124)
        at java.lang.Long.parse(Long.java:363)
        at java.lang.Long.parseLong(Long.java:353)
        at java.lang.Long.parseLong(Long.java:321)
        at java.math.BigDecimal.<init>(BigDecimal.java:344)
        at java.math.BigDecimal.<init>(BigDecimal.java:425)
        at com.example.galaxy.expense.MainActivity$1.onClick(MainActivity.java:48)
        at android.view.View.performClick(View.java:4780)
        at android.view.View$PerformClick.run(View.java:19866)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5257)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Solution

  • Apparently in my XML file I put the underline tags around 0.00 which gives the error when it is being converted to BigDecimal.. I removed the tags and everything works now