Tom Shaw
Tom Shaw

Reputation: 139

Why does the findViewById() method work only in the methods of the activity class but not in the class directly?

public class MainActivity extends AppCompatActivity {

       TextView name_header;

       //this results into an error
       name_header = (TextView) findViewById(R.id.name_header);

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

       //whereas, this works perfectly
       name_header = (TextView) findViewById(R.id.name_header);
...
 }
}

The problem is that I am trying to initialize the TextView object globally using the findViewById() but it throws an error at the runtime and then if I use it in the onCreate() or in any other method the initialization works just fine.

I am developing for API level 22 and above

Upvotes: 1

Views: 558

Answers (2)

Anirudhdhsinh Jadeja
Anirudhdhsinh Jadeja

Reputation: 763

As you know, setContentView(R.layout.menu_order); defines the layout to be attached with this particular java class. So, if you initialize any views from that XML it can't find it anywhere. Because it has no clue where to look for id name_header. So, it shows you error.

Now, I read your comment. And If I am correct you are initializing the view just after onCreate(). That means something like this.

...
public class MainActivity extends AppCompatActivity {
       @Override
       protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
      setContentView(R.layout.menu_order);
 }
   name_header = (TextView) findViewById(R.id.name_header);
}
...

So, this is same as this.

...
public class MainActivity extends AppCompatActivity {

       name_header = (TextView) findViewById(R.id.name_header);

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

}
...

So, it will give an error. You have to initialize the view inside any method. Because at first java is going to initialize the variables which is outside the method. And then it's gonna go inside any of other methods.

Upvotes: 1

Eric.1
Eric.1

Reputation: 71

Before the setContentView(...) function in onCreate(...) has been called, the layout(-file) has not been inflated/set yet. So there is nothing to look up an id in, yet.

As the Android docs describe it:

public T findViewById (int id)

Finds a view that was identified by the android:id XML attribute that was processed in onCreate(Bundle).

But since you already declared your TextView 'globally', you can just initialise it inside the onCreate function and use it anywhere else in the MainActivity without an issue.

Upvotes: 1

Related Questions