How to figure out which value is 0?

68 Views Asked by At

I got my 1st crash report for my app. It says there is a java.lang.ArithmeticException: divide by zero

The exception is on one of these two lines:

//sWP stands for "Screen Width in Pixels"
// sW stands for "Screen Width" The code is old though, so I may be incorrect for both variables.
//res is just getResources()
int sWP = sW / (res.getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT);
float bHeight = 50 * ((float)res.getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT);

Can DisplayMetrics.DENSITY_DEFAULT ever be zero? Or can getDisplayMetrics().densityDpi ever be zero?

1

There are 1 best solutions below

3
M.S. On

res.getDisplayMetrics().densityDpi will be 120, 160 or 240 (or something similar), see https://developer.android.com/reference/android/util/DisplayMetrics.html#densityDpi.

DisplayMetrics.DENSITY_DEFAULT constantly equals 160, see https://developer.android.com/reference/android/util/DisplayMetrics.html#DENSITY_DEFAULT.

res.getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT will return 0 because you divide int by int.

Change the first of the two lines to

int sWP = (int) sW / (((double) res.getDisplayMetrics().densityDpi) / DisplayMetrics.DENSITY_DEFAULT);

and it should work.