Reputation: 6748
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.
Upvotes: 1
Views: 693
Reputation: 19926
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()
.
Upvotes: 1
Reputation: 5095
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...
Upvotes: 1