Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
fixerIO with retrofit notes
capture json from curl or postman, like
{
"base": "USD",
"date": "2017-10-10",
"rates": {
"CAD": 1.2499,
...
...
}
}
visit http://www.jsonschema2pojo.org
plugin the json from above
check JSON, Gson, primitive types, use long, use doubles, include getters and setters, allow additional props
download zip and include in project
Start with fixerioexample
remember to add permission
<uses-permission android:name="android.permission.INTERNET" />
the following follows
https://www.lynda.com/Android-tutorials/Integrating-Android-Apps-RESTful-Web-Services/560057-2.html Chapter 7
but doesnt use android intent or intent service
load retofit2 and converter json library
File -> Project Structure -- Dependencies -> + -> Library Dependencies
copy retrofit dependency in build.gradle and change
compile 'com.squareup.retrofit2:retrofit:2.3.0'
to
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
resync gradle
create a new Service: FixerIOService
add with new Class, change to interface (not an Android Service!)
add to service interface
String BASE_URL = "http://api.fixer.io";
String PATH = "/latest";
String FEED = BASE_URL + PATH;
Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).
addConverterFactory(GsonConverterFactory.create()).build();
@GET(FEED) Call<FixerIOResult> getResponse(
@QueryMap Map<String, String> options
);
modify the onclicklistener to:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new FetchAsyncTask().execute(); // fetch the conv rates
}
});
modify FetcAsyncTask to
public class FetchAsyncTask extends AsyncTask<Void, Void, String> {
private String rateString;
@Override
protected String doInBackground(Void... v) {
FixerIOService service = FixerIOService.retrofit.create(FixerIOService.class);
Map<String, String> data = new HashMap<>();
data.put("base", "USD");
data.put("symbols", "GBP,JPY,CAD,AUS");
Call<FixerIOResult> call = service.getResponse(data);
FixerIOResult response;
try {
response = call.execute().body();
rateString = "" + response.getRates().getJPY();
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "doInBackground() " + e.getMessage());
}
return rateString;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.v("FixerIOExample", "conversion for JPY is :" + s);
result.setText("Conversion = " + s);
}
}
you'll want to come up with a better way to pass the target currency into the asynctask, this is just starter code
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.