0

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?

Foobar
  • 7,458
  • 16
  • 81
  • 161

1 Answers1

0

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.

M.S.
  • 312
  • 1
  • 12
  • Should I also change sWP to double? Also in this case res.getDisplayMetrics().densityDpi equals 320 – Foobar Oct 01 '16 at 20:19
  • @Roymunson Changing sWP to double does not make sense to me as you say _//sWP stands for "Screen width in Pixels"_. I am sorry, I forgot to cast to int. I will edit my answer. – M.S. Oct 01 '16 at 20:34
  • @Roymunson As to the value of 320 you get for densityDpi, somebody forgot to change the documentation for densityDpi from API 4 when introducing DENSITY_XHIGH in API 9. – M.S. Oct 01 '16 at 20:46