En Xin En Xin - 4 months ago 24
Android Question

Setting TypeFace NullpointerException

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

Answer

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

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

The following should work:

@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);
}