0

I want to add a TypeFace to my TextView. here's my Java code

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView helptitle = (TextView)findViewById(R.id.title_help);
        Typeface typeface = Typeface.createFromAsset(getAssets(), "beyond_the_mountains.ttf");
        helptitle.setTypeface(typeface);
        setContentView(R.layout.activity_help);
}

but when i run the app, i get a log cat error

Caused by: java.lang.NullPointerException
    at com.example.enxin.crystallise.Help.onCreate(Help.java:15)

There are many kinds of NullPointerException so I'm not sure how to solve this

En Xin
  • 929
  • 1
  • 6
  • 9
  • first make call setContentView(R.layout.activity_help); then findViewById. btw where did you put fonts file? – Siarhei Jul 16 '16 at 14:42

2 Answers2

2
 //You have mistaken the order
 setContentView(R.layout.activity_help);    
 TextView helptitle = (TextView)findViewById(R.id.title_help);
 Typeface typeface = Typeface.createFromAsset(getAssets(),    "beyond_the_mountains.ttf");
 helptitle.setTypeface(typeface);
En Xin
  • 929
  • 1
  • 6
  • 9
Cgx
  • 753
  • 3
  • 6
2

The problem is you're calling findViewById() before setting the content view.

findViewById() implicitly calls getWindow() which is still null at that time.

Call setContentView() before initializing your View:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_help);

    TextView helptitle = (TextView)findViewById(R.id.title_help);
    Typeface typeface = Typeface.createFromAsset(getAssets(), "beyond_the_mountains.ttf");
    helptitle.setTypeface(typeface);
}
earthw0rmjim
  • 19,027
  • 9
  • 49
  • 63