I have an app that changes the font typeface for some elements. It works well for most of the people, but maybe a 0.5% get an exception when trying to change the font. The significant part of the stack trace is this:
Caused by: java.lang.RuntimeException: native typeface cannot be made
at android.graphics.Typeface.<init>(Typeface.java:147)
at android.graphics.Typeface.createFromAsset(Typeface.java:121)
As I say, it works for most of the people, so I don't think it is a problem with the font file or my code. Any suggestions about how to solve this?
Edit: This is my code:
Typeface phoneticFont = Typeface.createFromAsset(getAssets(),
"fonts/CharisSILR.ttf");
TextView tv;
tv = ((TextView) findViewById(R.id.searchPronunciationTitle));
tv.setTypeface(phoneticFont);
This bug of Android OS could be the reason of your issue:
Typeface.createFromAsset leaks asset stream
Where are also a workaround in this bugreport:
I altered HTH's workaround so that the method does not assume the font path or format. The full path of the font asset must be submitted as a parameter. I also wrapped the call to createFromAsset() in a try-catch block so that the get() method will return null if the asset is not found.
public class Typefaces {
private static final String TAG = "Typefaces";
private static final Hashtable<String, Typeface> cache = new Hashtable<String, Typeface>();
public static Typeface get(Context c, String assetPath) {
synchronized (cache) {
if (!cache.containsKey(assetPath)) {
try {
Typeface t = Typeface.createFromAsset(c.getAssets(),
assetPath);
cache.put(assetPath, t);
} catch (Exception e) {
Log.e(TAG, "Could not get typeface '" + assetPath
+ "' because " + e.getMessage());
return null;
}
}
return cache.get(assetPath);
}
}
}
I followed some of the solutions found here, with no success. I thought it was something really obscure, as programmers often do. Then somewhere I read it could be related to the font path, gotcha:
Instead of:
Typeface phoneticFont = Typeface.createFromAsset(getAssets(),
"blanch_caps.ttf");
I changed to:
Typeface phoneticFont = Typeface.createFromAsset(getAssets(),
"fonts/blanch_caps.ttf");
And my file is in assets/fonts/blanch_caps.ttf. Not it works like a charm!
This error came up when the font was in the library asset folder. When I copied it into assets of the application which was using this library, the error disappeared.
It seems assets cannot be imported: Android Library assets folder doesn't get copied
And here are some other cases: Issue when using a custom font - "native typeface cannot be made"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With