Let me clarify my question OnCreate method is used to initialize view and flatten the layout , so I am thinking that if onCreate method is running before everything means my EditText field is empty means null so how this condition is working. But it working fine it means I am understanding something incorrectly. Please tell me what I am missing.
code snippet is taken from google codelabs where we are providing phone no. in editText and by clicking send button in device inbuilt keyboard we launch phone application to dial given number.
EditText editText = findViewById(R.id.editText_main);
if (editText != null) {
editText.setOnEditorActionListener
(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
return false;
}
});
}
Based on your code...
calling findViewById(R.id.editText_main);
can return null if a view with id "editText_main" was not found on the referenced xml layout of your activity, and when you call editText.setOnEditorActionListener
in such scenario a NullPointerException will be thrown causing your app to crash.
So if you're sure there will always be an id "editText_main" in your referenced layout then the "if condition" is useless. However if there is a possibility of not having a view with id "editText_main" assuming you set different layout based on some conditions then its important to check for nullity on your editText.
Example:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(a == b){
// Layout containing view with id "editText_main"
setContentView(R.layout.sample_activity_1);
}
else if(a == c){
// Layout without "editText_main"
setContentView(R.layout.sample_activity_2);
}
else{
// Layout without "editText_main"
setContentView(R.layout.sample_activity_3);
}
EditText editText = findViewById(R.id.editText_main);
// editText will be null if the referenced layout is not sample_activity_1
// which would cause a NullPointerException
editText.setOnEditorActionListener
(new TextView.OnEditorActionListener() {
});
}