views:

45

answers:

3

I'm getting null pointer exceptions when I try to initialize Button and EditText objects in global scope, can't figure it out. I've commented out everything but the bare minimum for the app to display my layout, but this still causes a crash:

private EditText addmoney = (EditText)findViewById(R.id.addmoney);

R.id.addmoney definitely, definitely exists. So what the heck? Is it impossible to declare EditText in global scope? I need to be able to call it from both onCreate and onPause in a class extending Activity, is there maybe another way I should be doing this?

EDIT:

I tried using shade's method of inflating the layout first but it causes errors, apparently your not allowed to use system services before onCreate() has been called and inflating a view requires one.

+3  A: 

You have to execute findViewById only after you have set the content for your current activity.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.home);
    addmoney = (EditText)findViewById(R.id.addmoney);//it knows in which file to search for the id
}
Pentium10
Exactly, this is because the activity needs to know which `R.id.addmoney` element it should use. Potentially the same element with the same id might exist in some other layout. This is why the `setContentview(...)` has to be invoked first.
Juri
@Juri: It's actually simpler than that. `findViewById` performs a simple tree traversal across your view hierarchy. If there's no view hierarchy there's not only nothing to find, there's nowhere to begin the traversal.
adamp
+1  A: 

Alternatively, you could do something like this:

private View dummy = (View) View.inflate(this, R.layout.dummy, null);
private EditText addmoney = (EditText) dummy.findViewById(R.id.addmoney);

... and in the onCreate (or wherever else):

setContentView (dummy);

Since you already have the parent of the EditText view instantiated, you can reference it without having a NPE.

NOTE: The first parameter of inflate is a Context. Therefore, you need a Context that is alive for this to work.

  • Ooops, wrong class :D
Shade
A: 

Makes sense, I never thought of that. Thanks for the replies!

jamzsabb