简体   繁体   中英

Cannot make a static reference to a non-static method - Android TabbedActivity

I'm new to Java and Android developing and I can't fix an error. I want to change the text of a TextView with a variable but the view class is static. Here's the code:

    public static class FirstTab extends Fragment {

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.first_tab, null);

        new Thread() {
            public void run() {

                MCQuery mcQuery = new MCQuery(serverAddress, 25565);
                QueryResponse response = mcQuery.basicStat();
                int Onlineplayers = response.getOnlinePlayers();
                Log.d("MCQuery", "" + Onlineplayers + " Online Players");

            }
        }.start();

        TextView onlinePlayersView = (TextView) findViewById(R.id.online_players);
        onlinePlayersView.setText(Onlineplayers);

        return v;
    }
}

The error is: "Cannot make a static reference to the non-static method findViewById(int) from the type Activity"

How can I solve this problem?

Now I'm gona make a wild guess: This is a nested class inside the declaration of some other class, and the method findViewById() is of the top level class but is not static? Well if that is correct that is the problem. When you define a inner class static it becomes, so to say, a separate top-level class. Because the method findViewById() is not static it requires an instance object of the top-level declared class, but class FirstView is now static - a totally separate class, which means to be instantiated it does not need an instance of the top-level class. Now this leads to the problem - FirstView don't need an object of the top-level class while the findViewById() does needs one. To fix it either change FirstView to non-static or findViewById() to static or explain what exactly you are doing outside this code and what your aim is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM