0

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?

Sid
  • 563
  • 1
  • 10
  • 28

1 Answers1

3

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.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Thanks, it works like that! But under my code construction, I need to call `createFromAsset()` in a static class in an `onCreateView` method. So after the `super.onCreate()` call here, I try `Typeface.createFromAsset(getActivity().getAssets(), "verdana.ttf")` and here again I get a `NullPointerException`. Is there a solution to this (or should I post this as a new question?). – Sid Aug 31 '14 at 15:59
  • @Sid: "But under my code construction, I need to call createFromAsset() in a static class in an onCreateView method" -- `onCreateView()` can call `getActivity()` to get a valid `Context` to use. Pass that `Context` into a static method that lazy-initializes your `Typeface`. "Is there a solution to this (or should I post this as a new question?)" -- I do not understand the rest of your comment, so if the advice I give here is insufficient, you may need to ask a fresh question, including the full stack trace and the source code. – CommonsWare Aug 31 '14 at 16:03