java.lang.NoSuchMethodError: No virtual method getTextBounds Error in android

1.5k views Asked by At

When I try to use the getTextBounds() method of Paint class in Android, I am getting errors on older version emulators (Marshmallow and Nougat 7.1.1). This is the error:

java.lang.NoSuchMethodError: No virtual method getTextBounds(Ljava/lang/CharSequence;IILandroid/graphics/Rect;)V in class Landroid/graphics/Paint; or its super classes (declaration of 'android.graphics.Paint' appears in /system/framework/framework.jar)

The issue does not seem to happen on android 10 emulator. I tried Invalidating caches and restarting as suggested in another answer, but it did not work.

2

There are 2 answers

2
Sideeg MoHammed On

This method was introduced in Android api 28 - check here - which means it won't be available in versions before.

This will work on devices running api 28+ and will throw that exception in devices running lower api levels.

Usually the correct way to do this is to introduce checks for the version:

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
// Safe to use getMccString
} else {
// Use something else that could work if there's something
}

Note that just because you can browse the source in your machine it doesn't mean the device running your app will have the same Android code running - most of the time it doesn't.

as mention here

0
KeeperMing On

When I use

Paint.getTextBounds(@NoNull CharSequence text, int start, int end, @NoNull Rect bounds); 

some devices throws

error:java.lang.NoSuchMethodError: No virtual method getTextBounds

replace:

Paint.getTextBounds(@NoNull String text, int start, int end, @NoNull Rect bounds);

it works hope help U