Two days ago I came across a post about creating an Inspiring Android App in One Hour. The post uses a library called Volley to consume REST API which brings a different quote every time a button is pressed. After reading the post, it made me remember that a few weeks earlier a friend asked me how I access REST APIs from Android. For the benefit of the friend, I decided to create this post using the same idea as the one from the post mentioned above.
I decided to write this post explaining how to use Retrofit 1.9 in Android which I am familiar with. Please note that by the time of this writing there is Retrofit 2 which I am yet to try.
I am not going to show you how to add create a project in Android Studio, however I will dig straight into the code. I know you know how to create the project and how to use Android Studio.
So we are going to jump straight into coding.
We start by adding our project dependencies. The dependencies I used for this project are;
- Butterknife
- Retrofit
- OKHttp
- Gson
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) . . compile 'com.jakewharton:butterknife:6.0.0' compile 'com.squareup.retrofit:retrofit:1.9.0' compile 'com.squareup.okhttp:okhttp:2.0.0' compile 'com.google.code.gson:gson:2.3' }
That's it for adding the dependencies for my project. At this time you may sync your project to download the dependencies. Next step is to add our POJO. We create a new Java class, model.Quote.class and we paste the code below.
public class Quote { @SerializedName("quoteLink") @Expose private String quoteLink; @SerializedName("quoteAuthor") @Expose private String quoteAuthor; @SerializedName("quoteText") @Expose private String quoteText; @SerializedName("senderName") @Expose private String senderName; @SerializedName("senderLink") @Expose private String senderLink; //Getters and Setters . . }
Next step is to add an interface which I called QuoteService.class with the code as below.
public interface QuoteService { @GET("/?method=getQuote&format=json&lang=en") void getQuote(Callback<Quote> qt); }
We edit our layout file to have two text views. I am using two since I am only showing the quote text and the quote author. My layout is very simple I will let the reader use their design skills to make this look beautiful.I have added two buttons which are optional here. One for New Quote and another one for Copying the quote text to clipboard. I have also added a progressbar which will be displayed as the application will be connecting and bringing the data from the server.
We have to change our activity so that the data is populated by the server. I will show you the part which is necessary for this application. I will not show you the progressbar and the clipboard copying button as those are out of the scope of this article.
//Quote.class private String quoteText = null; @InjectView(R.id.quoteView) TextView mQuoteView; @InjectView(R.id.quoteAuthor) TextView mQuoteAuthor; public static final String API_BASE_URL = "http://api.forismatic.com/api/1.0/"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_quote); ButterKnife.inject(this); mQuoteView.setText("From small beginnings come great things."); mQuoteAuthor.setText("Unknown"); addQuote(); } /* * Button to load a new quote and display it * */ @OnClick(R.id.new_quote) public void newQuoteClicked(View v) { addQuote(); } /* * Adds a quote from the API online and displays it on the screen * */ private void addQuote() { if (isOnline()) { showProgress(true); RestAdapter adapter = new RestAdapter.Builder() .setEndpoint(API_BASE_URL) .build(); QuoteService quoteService = adapter.create(QuoteService.class); quoteService.getQuote(new Callback<Quote>() { @Override public void success(Quote listQuote, Response response) { //quoteText = listQuote.getQuoteText() + " - " + listQuote.getQuoteAuthor(); showProgress(false); mQuoteView.setText(listQuote.getQuoteText()); mQuoteAuthor.setText(listQuote.getQuoteAuthor()); } @Override public void failure(RetrofitError error) { Log.e("retrofit", "failure: " + error.getMessage()); } }); } else { Toast.makeText(getBaseContext(), "Network isn't available", Toast.LENGTH_LONG).show(); } }
/* * check if the device is connected to the Internet * */ protected boolean isOnline() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); return netInfo != null && netInfo.isConnectedOrConnecting(); } //Do the showProgress() and the clipboard copy .
At this point our application is ready. Oops wait, we must add the permissions to use the Internet in our AndroidManifest.xml file. When all is done then voila, we have a working application.
Enjoy, and thanks to forismatic.com for the API and also to iteachyouhowtocode.com for the inspiration.