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?
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With