NullPointerException异常

NullPointerException异常

本文介绍了从Android Studio中的资源加载字体时,NullPointerException异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的Android应用程序中使用自定义字体。我遵循说明,并在Android studio中创建了一个资源文件夹,其中我放置了 verdana.ttf ,如图所示:





然后我在我的 MainActivity 活动中调用以下内容:

 code> public class MainActivity extends ActionBarActivity {

Typeface mainFont = Typeface.createFromAsset(getAssets(),verdana.ttf);

代码编译,但是当活动启动时,我得到一个 NullPointerException 上面的一行。我怀疑 verdana.ttf 文件可能已损坏,但尝试不同的字体时,错误仍然存​​在。清理项目也没有帮助。资产文件夹是否位于错误的位置?我可能会做错什么?

解决方案

您正在尝试调用 createFromAsset()从初始化程序。请在 super.onCreate()调用后将其移动到 onCreate()。在活动中继承的方法在此之前可能无效。


I would like to use a custom typeface in my Android app. I followed instructions and created an assets folder in Android studio in which I put verdana.ttf, as shown on the picture:

Then I call the following in my MainActivity activity:

public class MainActivity extends ActionBarActivity {

    Typeface mainFont = Typeface.createFromAsset(getAssets(), "verdana.ttf");

The code compiles, but when the activity is launched, I get a NullPointerException on the above line. I suspected the verdana.ttf file might be corrupted, but the error persists when trying different typefaces. Cleaning the project does not help either. Is the assets folder in the wrong location? What might I be doing wrong?

解决方案

You are trying to call createFromAsset() from an initializer. Please move this to onCreate(), after the super.onCreate() call. Methods you inherit in your Activity may not work before that point.

这篇关于从Android Studio中的资源加载字体时,NullPointerException异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 15:22