Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: Non-static method 'findViewById(int)' cannot be referenced from a static context

I am using Android Studio (Beta), and while using this java code in 'onCreateView()', I get an error.

ListView listView = (ListView) findViewById(R.id.someListView);

This is the error:

Non-static method 'findViewById(int)' cannot be referenced from a static context

How do I fix this?

like image 910
A_Bush Avatar asked Aug 18 '14 15:08

A_Bush


People also ask

How do you fix non-static method cannot be referenced from a static context?

There is one simple way of solving the non-static variable cannot be referenced from a static context error. In the above code, we have to address the non-static variable with the object name. In a simple way, we have to create an object of the class to refer to a non-static variable from a static context.

Why static method cannot access non-static methods?

In the static method, the method can only access only static data members and static methods of another class or same class but cannot access non-static methods and variables. Non-static method: Any method whose definition doesn't contain the static keyword is a non-static method.


1 Answers

Assuming you have a static fragment inner class inside an activity: you're trying to call the activity's findViewById() which you cannot in a static inner class that doesn't hold a reference to the parent.

In onCreateView() you need to call it on the root view you just inflated, e.g.

 ListView listView = (ListView) rootView.findViewById(R.id.someListView);
like image 151
laalto Avatar answered Sep 21 '22 05:09

laalto