Sid
Sid

Reputation: 573

NullPointerException when loading typeface from assets in Android Studio

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:

assets

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?

Upvotes: 0

Views: 629

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006849

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.

Upvotes: 3

Related Questions