Coder1
Coder1

Reputation: 13321

getString() causes null pointer reference in class that extends application

I have a class that extends application. I need to get a string from the strings.xml file.

I'm using this class to manage global state, so it is being loaded via the manifest.

Upon load, the getString() generates a null pointer reference.

How can I access the strings from this class?

public class MyApp extends Application {

public MyApp() {
    try {
        String apiurl = getString(R.string.api_url);
    }
    catch (Exception e) {
        Log.v("MyApp", e.toString());
    }
}

}

Upvotes: 1

Views: 493

Answers (1)

shanet
shanet

Reputation: 7324

You need to override the onCreate function rather than use a constructor.

So...

public void onCreate() {
   try {
      String apiurl = getString(R.string.api_url);
   }
   catch (Exception e) {
       Log.v("MyApp", e.toString());
}

http://developer.android.com/reference/android/app/Application.html#onCreate()

Upvotes: 2

Related Questions