Skip to content
Advertisement

Cannot make a static reference to the non-static method

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

JavaScript

This is the error message:

Error: Cannot make a static reference to the non-static method getText(int) from the type Context

How is this caused and how can I solve it?

Advertisement

Answer

Since getText() is non-static you cannot call it from a static method.

To understand why, you have to understand the difference between the two.

Instance (non-static) methods work on objects that are of a particular type (the class). These are created with the new like this:

JavaScript

To call an instance method, you call it on the instance (myObject):

JavaScript

However a static method/field can be called only on the type directly, say like this: The previous statement is not correct. One can also refer to static fields with an object reference like myObject.staticMethod() but this is discouraged because it does not make it clear that they are class variables.

JavaScript

And the two cannot work together as they operate on different data spaces (instance data and class data)

Let me try and explain. Consider this class (psuedocode):

JavaScript

Now I have the following use case:

JavaScript

What are the values?

Well

JavaScript

In other words, TTT is a datum that is shared by all the instances of the type. So it make no sense to say

JavaScript

So the question is why is TTT static or why is getText() not static?

Remove the static and it should get past this error – but without understanding what your type does it’s only a sticking plaster till the next error. What are the requirements of getText() that require it to be non-static?

Advertisement