0

I write a demo of fragment, and under android 3.0, the method getWidth() and getHeigh() is deprecated. and i read the api, found that getSize(point) is the same with the two method ,so i try it .

  Display d = wm.getDefaultDisplay();
  int width=0;
  int height=0;
  Point point = new Point(width,height);
  d.getRealSize(point);

but when i run the app ,there occur an error,is there anybody found such problem?:

02-01 03:13:06.548: E/AndroidRuntime(558): FATAL EXCEPTION: main
02-01 03:13:06.548: E/AndroidRuntime(558): java.lang.NoSuchMethodError: android.view.Display.getRealSize
02-01 03:13:06.548: E/AndroidRuntime(558):  at com.demo.fragment.FragmentDemoActivity.onCreate(FragmentDemoActivity.java:33)
02-01 03:13:06.548: E/AndroidRuntime(558):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048)
02-01 03:13:06.548: E/AndroidRuntime(558):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1700)
Charles Brunet
  • 21,797
  • 24
  • 83
  • 124
echo
  • 11
  • 1
  • 3

2 Answers2

3

The Display.getRealSize() method was added in API 17, which is Android 4.2. If you try to use it on a device below that, you will get a NoSuchMethodException as the method doesn't exist.

Display.getSize() was added in API 13, which is Android 3.2. You want to use the app on Android 3.0, which is API 11.

So for older devices, and even current ones (I am yet to hear of a deprecated method actually being removed from Android), you should use getWidth() and getHeight().

Or you could run the code in an if else statement, something like:

int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1){
    //Do something for API 17 only (4.2)
    //getRealSize()
}
else if (currentapiVersion >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2){
    // Do something for API 13 and above , but below API 17 (API 17 will trigger the above block
    //getSize()
} else{
    // do something for phones running an SDK before Android 3.2 (API 13)
    //getWidth(), getHeight()
}
Raghav Sood
  • 81,899
  • 22
  • 187
  • 195
0

use this code for both older and new versions.

private static Point getDisplaySize(final Display display) {

final Point size= new Point();
try {
    display.getSize(size); /// will support new versions
} catch (java.lang.NoSuchMethodError ignore) { // Older versions
    size.x = display.getWidth();
    size.y = display.getHeight();
}
return size;

}

Eldho NewAge
  • 1,313
  • 3
  • 13
  • 17