MrGibbage
MrGibbage

Reputation: 2646

Android resources as a member variable in the main activity

Working the android hello world, I next added some strings to the strings.xml resource file. I then tried setting a member variable of my main activity class to the value of one of the strings:

public class MyActivity extends Activity {
  /** Called when the activity is first created. */
  public String myString = getString(R.string.MY_STRING); // compiles, but crashes

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    TextView tv = new TextView(this); 
    tv.setText(myString);
    setContentView(tv);
  }     
}

When it crashes, I get this in the logcat: Unable to instantiate activity ComponentInfo{com.myclass}: java.lang.NullPointerException

So, am I doing it wrong, or is this expected behavior? Looking over the documentation, I don't see anything to lead me to think that the resources wouldn't be available while the main activity is being constructed.

http://developer.android.com/guide/topics/resources/accessing-resources.html

However, I am pretty sure this will work in other classes--just not the main activity class.

Upvotes: 1

Views: 722

Answers (1)

Richard Green
Richard Green

Reputation: 2062

I don't think you can call getString on the Activity class as it may not have been properly initialised yet. You may need to split the declaration (keep it as a public String) and then the assignment (move that to onCreate).

public class MyActivity extends Activity {
      /** Called when the activity is first created. */
      public String myString;

      @Override
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myString = getString(R.string.MY_STRING); // compiles, but crashes
        TextView tv = new TextView(this); 
        tv.setText(myString);
        setContentView(tv);
      }     
    }

Upvotes: 1

Related Questions