Cannot make a static reference to the non-static method

后端 未结 7 2144
长发绾君心
长发绾君心 2020-11-21 04:32

Building a multi-language application in Java. Getting an error when inserting String value from R.string resource XML file:

public static final         


        
7条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-21 05:09

    This question is not new and existing answers give some good theoretical background. I just want to add a more pragmatic answer.

    getText is a method of the Context abstract class and in order to call it, one needs an instance of it's subclass (Activity, Service, Application or other). The problem is, that the public static final variables are initialized before any instance of Context is created.

    There are several ways to solve this:

    1. Make the variable a member variable (field) of the Activity or other subclass of Context by removing the static modifier and placing it within the class body;
    2. Keep it static and delay the initialization to a later point (e.g. in the onCreate method);
    3. Make it a local variable in the place of actual usage.

提交回复
热议问题