0
Follow
5
View

Why we check EditText not equal to null in OnCreate method

cx8311841 注册会员
2023-01-26 08:54

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() {
   });
}
c26533806 注册会员
2023-01-26 08:54

The null check prevents a null pointer exception if you try to access the editText before the layout is inflated. But if you're setting this variable in the onCreate method after the call to inflate the layout then the editText shouldn't be null. The text property may be (since you haven't typed anything yet) but the component itself shouldn't be null.

About the Author

Question Info

Publish Time
2023-01-26 08:54
Update Time
2023-01-26 08:54