0

What's wrong with the following code?

I'm trying to use onResume method but it's crashing.

The IDs in the XML are correct.

public class MainActivity extends ActionBarActivity {
  TextView ford = (TextView) findViewById(R.id.krux);

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
  }

  @Override
  protected void onResume() {
    super.onResume();
    ford.setText("camphor");
  }
}
Dave Newton
  • 156,572
  • 25
  • 250
  • 300

1 Answers1

2

Use the findViewById after setting the layout. Currently you try to initialize the textview before you even set it.

public class MainActivity extends ActionBarActivity {
  TextView ford; 

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ford= (TextView) findViewById(R.id.krux);
  }

  @Override
  protected void onResume() {
    super.onResume();
    ford.setText("camphor");
  }
}
Orhan Obut
  • 8,638
  • 5
  • 30
  • 42
  • thabks its working but why cant i define the variable inside the onCreate method itself.. it will be carried to the onREsume anyways right? – user4698017 Apr 09 '15 at 16:32
  • @user4698017 If you declare it inside of `onCreate()` then it's scope will only exist in that method. If you declare it as a member variable (as in the examples you've been given) it will be visible in the whole activity. If you only need it in `onResume()` then you can declare **and** initialize it there instead of `onCreate()`. This is why code only answers aren't usually very good for SO – codeMagic Apr 09 '15 at 16:39