0

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.

ColonD
  • 954
  • 10
  • 28

2 Answers2

2

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

SkrewEverything
  • 2,393
  • 1
  • 19
  • 50
KeeperMing
  • 31
  • 1
1

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

Sideeg MoHammed
  • 375
  • 2
  • 10
  • So, is there any recommended method to do this pre 28? I only need the width of the text – ColonD Oct 22 '20 at 09:06
  • Study Android source code, Paint.java source, see both measureText and getTextBounds methods. You'd learn that measureText calls native_measureText, and getTextBounds calls nativeGetStringBounds, which are native methods implemented in C++. – Sideeg MoHammed Oct 22 '20 at 09:12