Getting data from APIs to Android application (Java)

Many services creating APIs and get public access to it. With API you can get service data and process it with your code. If you want to use data form API in your Android application, you need to create a JSON request. It’s very easy!

First, you need to get URL with a request to API. Everything you will need, you will find in the API documentation, just search and read ?

We have URL that calls API. In response, we will get JSON data. This request we can make in e.g. browser to test what we got form API. Paste URL to your browser and open it. You will see the block of text. It isn’t very readable but there is a way to format JSON data in the browser. There are many extensions that formatting JSON. In Chromium, I’m using JSON Formatter. Now, we can see what we got easily. That’s very helping when you don’t know what kind of data the API return and how the proper keys are named.

Making a request in Android

To make JSON request we will need to implement the Volley library. Volley will help us in making requests and it’s very easy to use. Here it is, code structure for the request:

First, we initialize the RequestQueue class, next we prepare our string with URL. Then, we creating JsonObjectRequest with parameters: request method – GET, string with URL, JSON with parameters to post, if you have some, if not pass null. In the end, we have success and error listener with methods onResponse() and onErrorResponse(). We need to complete these methods with code what to do on success and what to do on error. On success, we will get JSONObject and we can get data from it using methods like getJSONObject(), getJSONArray(), get() etc. On error, you need to handle the error and prepare the code, for example, to inform a user about the problem. Do it, please don’t live just comment with TODO 🙂 At the very end, add request object to queue.

Wrap your code in some method. We will need to call this method. If your app needs this data when you open the app, make a call in onCreate() method and if you want to update data via new request when user back to the app from pause, call this method again in onResume().

And that’s it! Now your application getting data from API, you can do it with this data whatever you want! Some inspiration, recently, I used API to get data about my top artists and songs I recently listened and I displayed it in my application. Now, for example, I have a very fast way to check how many songs I listened to today.

Read more articles about Java

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.