Code snippets below,
public class RelativeActivity extends Activity
{
// private Button ok_btn = (Button) findViewById(R.id.ok);
// private EditText edit = (EditText) findViewById(R.id.editText01);
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_relative);
Button ok_btn = (Button) findViewById(R.id.ok);
final EditText edit = (EditText)findViewById(R.id.editText01);
ok_btn.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), edit.getText().toString(), Toast.LENGTH_LONG).show();
}
});
}
which is right, however if i set both this instance of Button, ok_btn, and this instance of EditText, edit as private field, as shown in the commented out lines at top of the code, this would result in an error,why?
Thank you in advance,
this code make an error at run time because you are trying two access Button and EditText before setting an Layout for Current Window (Activity). and in default Activity layout these to Ui elements not exits that’s why you are getting Error.
solution if you just declare all UI elements before onCreate method of Activity an initialize all UI elements after setting Activity layout in which Ui elements you have added .
for example in your code :