tags:

views:

165

answers:

2

The question is quite simple. But I want to know where exactly do we make our references to the gui elements? As in which is the best place to define:

final EditText edit =  (EditText) findViewById(R.id.text_xyz);
 edit.getText.tostring();

When I try it doing inside the default oncreate() I get null values. So for best practice, do u recommend a separate class for referring these already defined gui elements in main.xml. From here we can call various methods of these elements like gettext or settext?

+1  A: 

Well, it depends on your needs. Very often I keep my references to widgets in activity (as a class fields) - and set them in onCreate method. I think that is a good idea
Probably the reason for your nulls is that you are trying to call findViewById() before you set contentView() in your onCreate() method - please check that.
Regards

Ramps
+2  A: 

If you are doing it before the setContentView() method call, then the values will be null.

This will result in null:

super.onCreate(savedInstanceState);

Button btn = (Button)findViewById(R.id.btnAddContacts);
String text = (String) btn.getText();

setContentView(R.layout.main_contacts);

while this will work fine:

super.onCreate(savedInstanceState);
setContentView(R.layout.main_contacts);

Button btn = (Button)findViewById(R.id.btnAddContacts);
String text = (String) btn.getText();
Eclipsed4utoo