NullPointerException when loading typeface from as

2019-09-07 12:38发布

问题:

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?

回答1:

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.