-2

I trying to develop an android app, where I need to make a static(PLACES_API_BASE) reference to a non-static variable.Please check out the below code.

private static final String PLACES_API_BASE= getResources().getString(R.string.places_api_base);

But, I am getting an error stating,

Cannot make a static reference to the non-static method getResources() from the type 

Is there any possible work around to achieve this. Please help. Thanks!

Dave
  • 297
  • 3
  • 4
  • 15

4 Answers4

0

No you cannot make a static reference to the non-static method because the method is "attached" to an instance (object scope) which the "static" reference (class scope) is not "aware" of.

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
0

No way. getResources is an instance method. So any way you should create an instance before calling it. And PLACES_API_BASE is and class constant, which does not belong to any instance.

PKopachevsky
  • 262
  • 1
  • 6
0

Here's how you can fix it:

private final String mPlacesApiBase;

// constructor
public YourClass(Context context) {
    mPlacesApiBase = context.getResources().getString(R.string.places_api_base);

If your class is an activity/service, put the initialization in onCreate() instead:

private String mPlacesApiBase;

@Override
public void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    mPlacesApiBase = getString(R.string.places_api_base);

I changed the variable name. By Java conventions, ALL_CAPS_IDENTIFIERS are for constants known at compile time and not for things initialized dynamically. The prefix m is the convention for member variables. I also removed the static as it doesn't seem to be necessary here.

laalto
  • 150,114
  • 66
  • 286
  • 303
  • I want the mPlacesApiBase to be static. I am using it else where so. I cant remove static modifier. – Dave Jan 14 '14 at 11:20
  • You can have it but you shouldn't need it. – laalto Jan 14 '14 at 11:22
  • I need it. I am using it else where.So how is it possible? – Dave Jan 14 '14 at 11:23
  • Bad practice. Your app will be dying ever so often. You can still use the @laalto solution. Just add static to the declaraction. The key thing is that it HAS to be initialized in a non static context (ex. the constructor) – Jitsu Sep 11 '14 at 13:16
-1

Create an object and then call method getResources() in a method or constructor.

rai.skumar
  • 10,309
  • 6
  • 39
  • 55
  • 2
    -1 you could also say: "make the method `getResources()` static. It doesn't answer the question but rather try to "patch" the problem without real understanding of the issue. Bad practice! – Nir Alfasi Jan 14 '14 at 04:50
  • @Dave has asked for a workaround. So i have tried to give way the same. – rai.skumar Jan 14 '14 at 05:06