1

I have a AppConstants class where I have some static variables and static methods. Variable like

public static final String BASE_URL = "http://www.somevalue.com/api/";
private static String MID_FIX_API;
public static final String API_CALL = BASE_URL + getMidFixApi() + "/" + GET_KEY(appContext, KEY_FOR_KEY);

As MID_FIX_API is private so I have its public getter/setter. When I set its value from another class by its setter method AppConstants.setMidFixApi("value"); and get its value from its getter method AppConstants.getMidFixApi(); Everything is fine till now
But
The problem comes when after the above lines I call static variable API_CALL shown in the code above that get value from the getter of the variable MID_FIX_API and return null despite of that we have passed value to it before.

This is the whole sequence of lines

AppConstants.setMidFixApi("getCategories");   // setting value
Log.e("InsideSuccess", "MID_FIX_API = " + AppConstants.getMidFixApi());  // working fine till here

Log.e("InsideSuccess", "API_URL = "+AppConstants.API_CALL);   // here I'm getting like this http://www.somevalue.com/api/null/somePostFix

Please point me what I'm doing wrong.

2
  • 1
    API_CALL is a compile time constant. Commented Oct 30, 2017 at 10:02
  • Thanks +1 for all the helpers. Commented Oct 30, 2017 at 10:08

2 Answers 2

1

As already mentioned the variable API_CALL is initialized once, with the current value of MID_FIX_API which initially is null.

A work around is to create a static method (getApiCall()) which just computes the value which earlier was staticly initialized, which would just look as easy as this:

public static String getApiCall(){
    return BASE_URL + getMidFixApi() + "/" + GET_KEY(appContext, KEY_FOR_KEY);
}

Which then can be called in an easy manner AppConstants.getApiCall().

Sign up to request clarification or add additional context in comments.

Comments

1

This has to to with initialisation order. When you call AppConstants.setMidFixApi("getCategories") the AppConstants class will be initialised before the value is set. Hence when the API_CALL is initialised, the MID_FIX_API is not yet assigned...

1 Comment

so I need to change API_Call value too while calling AppConstants.setMidFixApi("getCategories")?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.