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
  • 158,873
  • 26
  • 254
  • 302
  • 1
    Move `ford = (TextView) findViewById(R.id.krux);` line after `setContentView(R.layout.activity_main);` – ρяσѕρєя K Apr 09 '15 at 16:19
  • "It's crashing" is an incomplete diagnostic. Include the actual crash info. In any case, probably the `ford` value is going away. – Dave Newton Apr 09 '15 at 16:22
  • "your app has unfortunately stopped" – user4698017 Apr 09 '15 at 16:25
  • @user4698017 No no, the logcat. – Dave Newton Apr 09 '15 at 16:27
  • @user4698017 that's just a general message Android gives you when an app crashes not the error. See [What is a stacktrace](http://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors) – codeMagic Apr 09 '15 at 16:27
  • anyways i got it.. your method worked @prosper K but why on earth is it coming now.. ? i mean i made all the basic layout by defining the variable and all in the onCreate itself why would it fail there? – user4698017 Apr 09 '15 at 16:29
  • See the target link at the top. I've explained it there what the problem is. – codeMagic Apr 09 '15 at 16:31

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,756
  • 5
  • 32
  • 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