Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Aditya Pore
1,453 Pointsrefactor the Fun Facts app to use string resources
I was able to modify the string.xml under res folder. However while accessing the array in Java(FactBook.java) I am getting a null pointer exception.
Here is the code snippet;
import android.content.res.Resources; public class FactBook { Resources res = getResources();// cannot resolve getResources() method public String[] mFacts = res.getStringArray(R.array.app_facts); ................. }
When i tried to extend Factbook to Activity viz,
public class FactBook extends Activity {
} The IDE recognizes the getResources method. But I get a null pointer exception stating that getResources is trying to reference null object.
I tried it using Context Class also as follows: Context ctx; String []mFacts = ctx.getResources().getStringArray(R.array.app_facts);
This also did not work out ... same error Null Pointer exception.
I have declared a string array in strings.xml under res/values folder ..
Please help
2 Answers
Seth Kroger
56,416 PointsThe problems with either approach is that the Activity/Context isn't properly initialized at that point for the getResouces call to work.
I can think of two different ways of doing this, both involve adding a constructor to FactBook. Either with a String array, or a Context and int id as arguments. You would then call that constructor in onCreate() instead of with the member declaration.
// Using the FactBook(String[]) version
Resources res = getResources();
mFactBook = new FactBook(res.getStringArray(R.array.app_facts));
Ben Deitch
Treehouse TeacherHey Aditya! We can't just use any ol' Context when we want to call getResources(). We need to use our application's context which isn't available until we're creating our activity.
You'll need to add a constructor to your FactBook class that takes in a Context, and initialize your FactBook in the onCreate method of FunFactsActivity while passing in a Context (using either the 'this' keyword or 'getApplicationContext()').
Aditya Pore
1,453 PointsThanks!
Aditya Pore
1,453 PointsAditya Pore
1,453 PointsThanks a lot it worked :)