In the process of error localization, I found that the application "flies" on the line with the findViewById method (I removed all unnecessary from the code, but I have everything that I haven’t put in here, commented out):

 public class AddItem extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_item); } LinearLayout AddItemContainer = (LinearLayout) findViewById(R.id.AddItemContainer); } 

It is strange that everything worked fine before, and I have not touched this line since. What could be the reason?

(We get into this activity from another activity; this also works fine if we remove the line with findViewById ).


Update

  • Cut from error message:

    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window $ Callback android.view.Window.getCallback ()' on a null object reference

  • what mistake? check the existence of AddItemContainer and activity_add_item - Valera Kvip
  • Error message posted. I copied the AddItemContainer from XML, so there can be no error. activity_add_item also exists, otherwise the markup would not be displayed with a commented out line with findViewById. - Lateral Gleb

1 answer 1

The findViewById method cannot be called before the onCreate method, and it is meaningless until setContentView. And you use it to initialize the field, that is, it is called even before the constructor ... At this point, nothing has been initialized yet in the activation, she does not know anything about any views.

  • From a code point of view, findViewById is just called after onCreate ... Does this mean that the code after OnCreate is executed earlier? - Bokov Gleb
  • 2
    It is called when the class field is initialized; the class field is initialized when an instance of the class is created before calling its constructor. And all this happens long before calling the onCreate method. The fact that you describe the field below does not affect the description of the method, except for annoying those who are used to reading code written according to generally accepted rules, where in particular the fields are always described before the methods. In general, learn the basics of Java ... - xkor Sept
  • Well, thank you for the answer, now this error has been fixed. But what if I need the AddItemContainer variable in several helper methods outside of OnCreate? (It would be necessary only in one - it would be possible to declare a variable in this method, but there are several of them). - Bokov Gleb
  • Well, declare a field in the class description, and assign a value inside onCreate. Husband, after that you can use its value anywhere) - xkor
  • Thank you very much! Now everything is great! :) - Side by Gleb