lolttr11 :
Trying to get a response from server failed constantly. the JSON I'm trying to GET is this :
and I'm reading it right into "response" object and "rates" object inside it. (code attached below)
The response object:
public class Response {
public boolean success; // changed to boolean, was string before
public int timestamp;
public String base;
public String dateString;
public Rate rates;
}
The rate object:
public class Rate {
public static float ILS;
public static float EUR;
public static float USD;
public static float AUD;
public static float CAD;
public static float GBP;
public static float JPY;
public static float RUB;
public static float getConversionRate(String baseRateName, String targetRateName) {
Map<String,Float> rates = new HashMap<String,Float>();
rates.put("ILS",ILS);
rates.put("€",EUR);
rates.put("$",USD);
rates.put("AUD",AUD); // sign same as dollar, we wont use it
rates.put("CAD",CAD); // sign same as dollar, we wont use it
rates.put("£",GBP);
rates.put("¥",JPY); // yen, japan
rates.put("RUB",RUB); // rubel, russia
Float baseRate = rates.get(baseRateName);
Float targetRate = rates.get(targetRateName);
if (baseRate == null) {
baseRate = 1.0f;
}
if (targetRate == null) {
targetRate = 1.0f;
}
// return the conversion rate
return targetRate / baseRate;
}
}
The actuall call in main activity:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://data.fixer.io/")
.addConverterFactory(GsonConverterFactory.create())
.build();
FixerApi fixerApi = retrofit.create(FixerApi.class);
Call<Response> call = fixerApi.getResponse();
call.enqueue(new Callback<Response>() {
@Override
public void onResponse(Call<Response> call, retrofit2.Response<Response> response) {
if (!response.isSuccessful()) {
fixerRate.setText("Code: " + response.code());
return;
}
// if successful!
fixerResponse = response.body();
}
@Override
public void onFailure(Call<Response> call, Throwable t) {
Toast.makeText(getApplicationContext(),"Failed to get response from server", Toast.LENGTH_SHORT).show();
}
});
SkypeDogg :
I see one thing, which isn't right. Since you don't use @SerializedName
annotations, you should change dateString
to date
so it match with API (look as JSON, name of the field is "date", not "dateString").
Second thing is check please, if you need front slash after your URL inside BASE_URL
. I used to call methods without it, and I didn't have front slashes before certain methods either.