1

I am trying to use a custom font within a TextView of an Android Studio application, but am getting the following error:

enter image description here

It's a null pointer exception; in the below code, txt is null for some reason:

Java:

    TextView txt;

    txt.setText("A");


    txt = (TextView) findViewById(R.id.custom_font);
    Typeface font = Typeface.createFromAsset(getAssets(), "fonts/Grundschrift.ttf");
    txt.setTypeface(font);

XML:

android:id="@+id/custom_font"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="A"

Thanks!

Eddev
  • 890
  • 1
  • 10
  • 21

4 Answers4

3

With this part of your,

TextView txt;
txt.setText("A");

implies that you are calling a method setText() in a null object. To use this method, you have to first initialize the TextView.

so change this

TextView txt;
txt.setText("A");

txt = (TextView) findViewById(R.id.custom_font);
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/Grundschrift.ttf");
txt.setTypeface(font);

to

TextView txt; 
txt = (TextView) findViewById(R.id.custom_font);
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/Grundschrift.ttf");
txt.setTypeface(font);
txt.setText("A");
Inducesmile
  • 2,475
  • 1
  • 17
  • 19
1

The line: Caused by: java.lang.NullPointerException: Attempt to invoke the method 'void android.widget.TextView.setText(java.lang.CharSequence)... makes me assume that the ploblem is you call txt.setText("A"); before casting txt = (TextView) findViewById(R.id.custom_font);.

Instead you should do like this:

TextView txt = (TextView) findViewById(R.id.custom_font);
txt.setText("A");
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/Grundschrift.ttf");
txt.setTypeface(font);
gatteo
  • 1,382
  • 2
  • 10
  • 17
1

Try to change your code like the below code:

...
Typeface font = Typeface.createFromAsset(getContext().getAssets(),  "fonts/Grundschrift.ttf");
...

View's getContext() method to get the current context.

Krish Munot
  • 1,093
  • 2
  • 18
  • 29
pRaNaY
  • 24,642
  • 24
  • 96
  • 146
1

You are using txt before initializing, so this one causes a null pointer exception.

Before accessing any variable or object you have to initialize it properly.

like txt = (TextView) findViewById(R.id.custom_font);

txt.setText or something

Kiran Rajam
  • 186
  • 5