Sarah Pöhler Sarah Pöhler - 1 month ago 9x
Android Question

Custom Font for an Android App

I tried to add a custom font in my app. The method creating a typeface object and putting a font in it worked. Now I want to make a class for the custom font for having a cleaner code.

CustomFont class:

public class CustomFont extends AppCompatActivity {

private final Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/Slabo.ttf");

public CustomFont(TextView textView) {

and now I am trying to add this font to a textview:

public class MainActivity extends AppCompatActivity {

private Typeface typeface;
private CustomFont customFont;
private TextView textview;

protected void onCreate(Bundle savedInstanceState) {

//typeface = Typeface.createFromAsset(getAssets(), "fonts/Slabo.ttf"); // works
textview = (TextView) findViewById(;
//textview.setTypeface(typeface); // works

customFont = new CustomFont(textview); // does not work


but if I run this project I get this exception:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.AssetManager android.content.Context.getAssets()' on a null object reference


first of all CustomFont should not be activity.It should be normal class.

public class CustomFont {

    private Typeface typeface;
    public CustomFont(Context context) {
        typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Slabo.ttf");
    public void setFont(TextView textView) {

And call it from your MainActivity

customFont = new CustomFont(this);