Skip to content

Instantly share code, notes, and snippets.

@mislavs
Created October 29, 2014 20:04
Show Gist options
  • Save mislavs/5ed9da16434a4876d9d1 to your computer and use it in GitHub Desktop.
Save mislavs/5ed9da16434a4876d9d1 to your computer and use it in GitHub Desktop.
Simple REST Client implementation using Retrofit. Interfaces are declared in the GoogleBooksInterfaces file.
package com.msvs.bookshelf.retrofit;
import com.msvs.bookshelf.events.BookFoundEvent;
import com.msvs.bookshelf.model.entities.Author;
import com.msvs.bookshelf.model.entities.Book;
import com.msvs.bookshelf.model.entities.Category;
import com.msvs.bookshelf.retrofit.model.Item;
import com.msvs.bookshelf.retrofit.model.QueryResult;
import java.util.ArrayList;
import java.util.List;
import de.greenrobot.event.EventBus;
import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class Client {
private final String API_URL = "https://www.googleapis.com/books/v1";
private final String ISBN_QUERY_PREFIX = "isbn:";
private static Client mInstance;
private Interfaces.GoogleBooksService mService;
private Client(){
RestAdapter mRestAdapter = new RestAdapter.Builder()
.setEndpoint(API_URL)
.build();
mService = mRestAdapter.create(Interfaces.GoogleBooksService.class);
}
public static Client getInstance() {
if (mInstance == null) {
mInstance = new Client();
}
return mInstance;
}
public void getBookByIsbn(String isbn) {
Callback<QueryResult> cb = new Callback<QueryResult>() {
@Override
public void success(QueryResult result, Response response) {
//create objects from the query result
Item queryResult = result.getItems().get(0);
Book book = new Book(queryResult);
List<Author> authors = new ArrayList<Author>();
for (String author : queryResult.getVolumeInfo().getAuthors()) {
authors.add(new Author(author));
}
List<Category> categories = new ArrayList<Category>();
for (String category : queryResult.getVolumeInfo().getCategories()) {
categories.add(new Category(category));
}
EventBus.getDefault().post(new BookFoundEvent(book, authors, categories));
}
@Override
public void failure(RetrofitError error) {
}
};
mService.getBookByIsbn(ISBN_QUERY_PREFIX + isbn, cb);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment