Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null pointer exception while importing a font in android

I am trying to import a font. Looked for some tutorials online and used the instructions. So far I've imported the font onto the assets folder. This is the code that I am using to declare my font type.

Typeface localTypeface1 = Typeface.createFromAsset(getAssets(), "arial.ttf");

I keep getting null pointer exception when I call it.

TextView txtTab = new TextView(this);
txtTab.setTypeface(localTypeface1);

What could be the problem ? This is the exact error in logcat.

11-17 13:10:41.024: E/AndroidRuntime(2262): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{se.copernicus.activity/se.copernicus.activity.Secondactivity}: java.lang.NullPointerException
11-17 13:10:41.024: E/AndroidRuntime(2262): at android.content.ContextWrapper.getAssets(ContextWrapper.java:74)

This is line 74

Typeface localTypeface1 = Typeface.createFromAsset(getAssets(), "arial.ttf");

enter image description here

like image 650
Vinoth Avatar asked Nov 17 '11 07:11

Vinoth


People also ask

How do I fix NullPointerException in Android?

How to fix the NullPointerException? To avoid NullPointerException we have to initialize the Textview component with the help of findviewbyid( ) method as shown below. The findViewbyId( ) takes the “id” value of the component as the parameter. This method helps locate the component present in the app.

How do I fix null pointer exceptions?

NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.

What is NullPointerException in Android?

NullPointerException is a runtime exception in Java that occurs when a variable is accessed which is not pointing to any object and refers to nothing or null. Since the NullPointerException is a runtime exception, it doesn't need to be caught and handled explicitly in application code.

What is the NullPointerException is it checked or not?

NullPointerException is an unchecked exception and extends RuntimeException class. Hence there is no compulsion for the programmer to catch it.


2 Answers

What I have seen is that, Android cannot read some ttf files. (maybe the file is corrupted?)

I was not able to use a ttf file in my app but another app in my phone was able to read the same ttf file. (I used the same code as above, tried cleaning, replacing it diff folders nothing seemed to work)

Ended up using a different font file altogether. (Had no issues with this file with the same code!)

like image 199
bluefalcon Avatar answered Oct 02 '22 15:10

bluefalcon


Did you try moving your font directly into assets? (Not in the fonts folder), and getting rid of the fonts folder?

like image 36
Guillaume Avatar answered Oct 02 '22 16:10

Guillaume