1

I am trying to get the screen size on my emulator (API 7) with this code:

float scaledDensity = this.getResources().getDisplayMetrics().scaledDensity;

Now I try to use scaledDensity

with this code:

int width = (width / ((int) scaledDensity)) / 7;

and I get this exception

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tomer.workoutlog2/com.example.workoutlog.SimpleCalendarViewActivity}: java.lang.ArithmeticException: divide by zero

Full code:

Display display = ((WindowManager) getSystemService(WINDOW_SERVICE))
                .getDefaultDisplay();
        int width = 0;

        if (android.os.Build.VERSION.SDK_INT >= 13) {
            Point size = new Point();
            display.getSize(size);
            width = size.x;

        } else
            width = display.getWidth();

        float scaledDensity = this.getResources().getDisplayMetrics().scaledDensity;

        width = (width / ((int) scaledDensity)) / 7;

On my real device I don't get this error. Maybe, is the problem with the emulator?

Divya Jain
  • 393
  • 1
  • 6
  • 22
dasdasd
  • 1,971
  • 10
  • 45
  • 72

4 Answers4

0

for API 7 you can use the following code, it is deprecated from API 13

Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
DevZer0
  • 13,433
  • 7
  • 27
  • 51
0

scaledDensity() returns a float. Sure you are not accidentally doing a integer division with an float less than 1.0f?

mach
  • 8,315
  • 3
  • 33
  • 51
0

Try this code:

DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
float scaleFactor = displaymetrics.density;
Renan Bandeira
  • 3,238
  • 17
  • 27
0

Try this...

DisplayMetrics displaymetrics = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
            int height = displaymetrics.heightPixels;
            int width = displaymetrics.widthPixels;
Hariharan
  • 24,741
  • 6
  • 50
  • 54