0

In many tutorials on developing mobile applications in java in android studio, I see that almost everyone writes findViewById in the onCreate method, and I write immediately when defining the field (Example in the code below), and I don`t understand why everyone writes component search by ID in the onCreate method, although there seemed to be no differences, Or are they there?

As i do:

private Button asIDo = findViewById(R.id.btn_main);

As others do:

   private Button other;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        other = findViewById(R.id.btn_main);

    }

Is there a difference in this and what is it? I'm just a beginner and I don't know what the difference is, although it works the same way. Thanks for the answer and sorry for such a dumb question :)

2 Answers 2

1

The difference here is the timing. If you call findViewById on the field declaration, you are ignoring the activity lifecyle. So if your code run before the layout is inflated, then you can get a null pointer exception.

The right approach is to call the findViewById inside the onCreate method, becuase you are sure your layout is properly inflated and you are ready to find the view.

The lifecycle:

// ---> findViewHere is wrong since you don't have the properties set, either the view inflated
1. onCreate -> The view is inflated and all properties are set
// ---> Here is a good timing to find your view ;)
2. onStart -> The view is now visible to the user (but can't interect with it)
3. onResume -> Now the user can interect with the view
0

Generally you want to do it in onCreate. The reason is performance- if you do it in onCreate and store it, you only find it once. If you do it whenever you need it, you have to find it every time. Finding it requires walking the tree of views and checking each one, which is an O(n) operation based on the number of views- the more views on screen, the slower it is. It's preferable to do that one time and cache the results. Its slightly trading memory (the space to store the variable) for time (the time spent on subsequent lookups).

Not the answer you're looking for? Browse other questions tagged or ask your own question.