Search code examples
javaandroidandroid-studiorealm

Java float comparison is not working on RealmObject on Android


[edit]

This problem only occured due to RealmProxy class not giving correct value in debug mode on Android Studio. Read accepted answer for a good practise.

[Original question]

I have _allowedPercentageDiscount = 0.0 and perentageDiscount = 1.0, First I tried with

if(_allowedPercentageDiscount < percentageDiscount)
//do something

I also tried with

 if (Float.floatToIntBits(_allowedPercentageDiscount) < Float.floatToIntBits(percentageDiscount)) {
            //but it never works
        }

but it never result true. Then, after some search, I tried with Float.compare but it still did not result true. Magically it gives correct result in evaluation window. (Android Studio).

enter image description here

What the hell is wrong and what to do?

//=============== Edit

Full Code information requested in comments: I have a Product class which is:

class Product{
     public float _allowedPercentageDiscount, _discountPercentage;

     public float setDiscountPercentage(float percentageDiscount) {
       if (_allowedPercentageDiscount < percentageDiscount) {
           percentageDiscount = _allowedPercentageDiscount;
       } else if (percentageDiscount < 0)
           percentageDiscount = 0;
       return this._discountPercentage = percentageDiscount;
    }
}

Now I am calling this method on a list of Products from another class (Android Fragment). But condition is not working and discount is set to all products without their _allowedDiscountLimit. Stream support for java 6,7 in Android using Lightweight-Stream-API.

private void applyDiscountPercentage(int discountPercentage) {
     Stream.of(cartProducts).forEach(product -> product.setDiscountPercentage(discountPercentage));
}

Solution

  • The problem was not in the code or float but in the way Realm.io classes behave on Android, especially in debug mode related to concept of zero-copy. Any class implementing RealmModel or RealmObject will not give you correct variable value when you are debugging. Mentioned here Realm debugging and testing.

    Hence, in this question case, for example, _allowedPercentageDiscount was having value 15 which should have been different for each of the item. the value 15 assigned mistakenly somewhere else in the logic, got me to stuck in the line which need to act on this value.

    Result:

    You need to take extra care when debugging using Realm classes on Android in calculations and algorithms. As you can't see realm objects variable values in debugging mode, you can export those classes to normal mode in the time of debugging/development using Realm.copyFromRealm(). After success you can use the RealmResults for performance and zero-copy realm implementation.