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

5

16

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?

Respirator answered 18/8, 2014 at 15:38 Comment(0)
P
30

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);
Ptarmigan answered 18/8, 2014 at 15:49 Comment(0)
K
2

onCreateView() shouldn't be a static method (I'm assuming you are defining it within an Activity class), so you must be doing something wrong.

Krieger answered 18/8, 2014 at 15:40 Comment(0)
B
2

If you are using it in an static AsyncTask, or any other class, you can pass the activity as a parameter to a method or constructor, for example:

activity onCreate:

//Pass activity variable (this)
new Main2Activity.MyTask().execute(this);

class inside activity:

private static class MyTask extends AsyncTask<Object, Void, String> {

        Main2Activity activity;

        @Override
        protected String doInBackground(Object... params) {
            activity = (Main2Activity)params[0];
            ....
        }

        @Override
        protected void onPostExecute(String str) {
            // Use parameter activity passed to class
            WebView webView = activity.findViewById(R.id.web_view);
            webView.loadData(str, "text/html; charset=UTF-8", null);
        }
Biannulate answered 7/6, 2018 at 23:10 Comment(0)
Z
0
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.frag_layout, container, false);
    ListView listView = (ListView) view.findViewById(R.id.listviewID);
    context = getActivity();
    return view;
}

You can implement this now... Use view variable to access xml ui things in oncreateView and getActivity().findViewById(...) to access other then onCreateView() Method.

Zapateado answered 18/8, 2014 at 15:55 Comment(0)
B
0

Inside Activity class

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

OR

to create inside fragmentClass(static)

  static ListView listView;
  listView = (ListView) getActivity().findViewById(R.id.someListView);
Bridging answered 24/10, 2017 at 19:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.