adding custom font in my app

2019-08-28 00:23发布

while adding custom font in my app, it's crashing some time. But most of the time it get executed smoothly.

i'm using following code.

try {
// Get the typeface 
ShravyaApp.appTypeFace = Typeface.createFromAsset(getApplication().getAssets(),
                            "kadage.ttf");
Log.d("font","in type="+ShravyaApp.fontName);
Log.d("font","type face="+ShravyaApp.appTypeFace);
                     } 
catch (Exception e) 
{
ShravyaApp.appTypeFace = Typeface.createFromAsset(getApplication().getAssets(),
"kadage.ttf");
Log.d("font","in catch typr="+ShravyaApp.fontName);
Log.d("font","type face="+ShravyaApp.appTypeFace);
//Log.e(TAG, "Could not get typeface '" +   + "' because " + e.getMessage());
e.printStackTrace();        
}

The Error i'm getting is :

NullPointerException at android.graphics.Typeface.nativeCreateFromAsset(Native Method) at android.graphics.Typeface.createFromAsset(Typeface.java:280)

3条回答
闹够了就滚
2楼-- · 2019-08-28 00:45

I am guessing getApplication() is the function that returns a null pointer. It needs to be called in the onCreate(), not in the constructor. We need more context to be sure.

Also you can set a breakpoint catching null pointer exceptions in the debug mode.

查看更多
趁早两清
3楼-- · 2019-08-28 01:02

This could be IO Exceptions in the nativeCreateFromAsset. Also this can be because you are calling this method before Activity onCreate().

Any way try using retry mechanism with 100 milliseconds sleeping between retries, there is no reason that it will not work, unless some bug in the user device.

查看更多
来,给爷笑一个
4楼-- · 2019-08-28 01:06

Why place the same code in both try and catch?

I suggest you use a Typface-cache (example here) and if your app really requires the font, you may want to refactor your method into a recursive one and as Babibu said, pause in between.

查看更多
登录 后发表回答