Skip to content

Instantly share code, notes, and snippets.

@miquelbeltran
Created May 27, 2017 13:18
Show Gist options
  • Select an option

  • Save miquelbeltran/1681d513acde37ede2be6fc2367ef34b to your computer and use it in GitHub Desktop.

Select an option

Save miquelbeltran/1681d513acde37ede2be6fc2367ef34b to your computer and use it in GitHub Desktop.
public class MainActivity extends AppCompatActivity {
// Removed members for example
// Retrofit Service, we will move this out of the MainActivity
GoogleBooksService service;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Retrofit configuration, we will move this out too
Retrofit retrofit = new Retrofit.Builder()
// Base URL can change for endpoints (dev, staging, live..)
.baseUrl("https://www.googleapis.com")
// Takes care of converting the JSON response into java objects
.addConverterFactory(GsonConverterFactory.create())
.build();
// Create the Google Book API Service
service = retrofit.create(GoogleBooksService.class);
// Init the views here, code removed for the example
// Load the saved books list from the previous response on device rotation
if (savedInstanceState != null) {
Book[] books = (Book[]) savedInstanceState.getParcelableArray(SEARCH_RESULTS);
adapter.addAll(books);
}
}
private void performSearch() {
String formatUserInput = getUserInput().trim().replaceAll("\\s+", "+");
// Calling Retrofit inside the MainActivity
service.search("search+" + formatUserInput)
// enqueue runs the request on a separate thread
.enqueue(new Callback<BookSearchResult>() {
// We receive a Response with the content we expect already parsed
@Override
public void onResponse(Call<BookSearchResult> call, Response<BookSearchResult> books) {
updateUi(books.body().getBooks());
}
// In case of error, this method gets called
@Override
public void onFailure(Call<BookSearchResult> call, Throwable t) {
t.printStackTrace();
}
});
}
// More code has been removed from the example
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment