空指针异常使用类加载器从资产获取字体文件时

时间:2013-03-14 14:03:58

标签: android classloader assets

我有这段代码从assests文件夹中获取字体文件:

public static Typeface getMyFont(Context context, String resource) {
    InputStream is;
    Typeface font = null;
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

    AssetManager assetManager = context.getResources().getAssets();

    try {
        is = classLoader.getResourceAsStream(resource);
        is = assetManager.open(resource);
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while ((line = br.readLine()) != null) {
            Log.e("wwwww", line);
        }
        br.close();
        font = Typeface.createFromAsset(context.getAssets(), line);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return font;
}

这里资源是字体/ MYFONT.ttf在assests文件夹中链接(快捷方式),但我在这一行得到nullpointer异常:

font = Typeface.createFromAsset(context.getAssets(), line);

2 个答案:

答案 0 :(得分:1)

    my_font = Typeface.createFromAsset(context.getAssets(), "fonts/MYFONT.ttf"); 

答案 1 :(得分:1)

我也遇到了同样的问题,你可以尝试用try& amp; catch块来捕获空指针异常,因此,在我的情况下,

Typeface comingsoon = Typeface.createFromAsset(getApplicationContext().getAssets(), "ComingSoon.ttf");

成为

try{
    Typeface comingsoon = Typeface.createFromAsset(getApplicationContext().getAssets(), "ComingSoon.ttf");
}
catch(NullPointerExecption e){
     //...
}