Use API in android app in just 7 simple steps

Use API in android app in just 7 simple steps

In this post you will learn about API’s and how to fetch live data from the internet and provide data within your android app.

After following this post ,you would be able to implement any API within your app which would be useful for your large scale application. We will use openweathermap API in this tutorial. So let’s get started but wait do you know what is an API? If not then don’t worry I’ll explain you what is an API and I promise that you will not again search for what is an API?

What is an API

According to Wikipedia ,In computer programming, an application programming interface is a set of subroutine definitions, communication protocols, and tools for building software. In general terms, it is a set of clearly defined methods of communication among various components. A good API makes it easier to develop a computer program by providing all the building blocks, which are then put together by the programmer.

Not yet clear what is an API? We’ll break it down for you.

So basically it is an intermediary software that allows two applications to talk to each other. For example , You want to book your air ticket from indigo. Now you may go to the indigo website and book it. But how many of  us does that? Very rarely we do that. We use third party services like MMT ,Paytm etc.. So developers use this to get data from main server or for much more additional features.

Another example ,You login/signup to different websites that gives various options to you to sign up to their website. That may include Facebook ,google signup etc…

Get your API key

To start using application programming interface services of any organization ,we need to register and get the key from them. In this tutorial we’ll use openweathermap .

Get the API key by registering to openweathermap. The key is a unique identifier to the API provider. Follow the documentation there and get started.

You need to follow the guides properly as you need to understand what the provider provides ,So that you could use it in your application to display live data.

Let’s Code

Open Mainfest.xml and give it a permission to internet service as we are going to use internet service in app.

Copy the below code in activity_mamin.xmlm

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/winter"
    tools:context="com.example.studio.myweatherapp.MainActivity">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="24dp"
        android:fontFamily="cursive"
        android:text="Get Weather"
        android:textColor="@android:color/background_dark"
        android:textSize="50sp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/getCity"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Paris"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="24dp"
        android:background="@color/colorAccent"
        android:paddingBottom="10dp"
        android:paddingLeft="30dp"
        android:paddingRight="30dp"
        android:paddingTop="10dp"
        android:text="Get that"
        android:textColor="@android:color/background_light"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/getCity" />

    <TextView
        android:id="@+id/result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="24dp"
        android:text="TextView"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button"
        tools:layout_editor_absoluteY="234dp" />
</android.support.constraint.ConstraintLayout>

We are going to perform network request using volley library. Why volley? Because its simple and convenient unlike using asynctask request. Using volley we don’t need to worry about UI thread etc..

 In order to perform network request we need some boiler plate codes which performs the request. We need not worry about how that code works as it is a boiler plate code .It’s just needed in order to use volley. So copy these below lines of code in a class and named it as mySingelton.java .

If you are not familiar with volley then I would recommend to first learn about volley. We already have a post on volley ,So have a look on that.

package com.example.studio.myweatherapp;

import android.content.Context;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;


public class MySingleton {

    private static MySingleton mInstance;
    private RequestQueue requestQueue;
    private static Context mCtx;

    private MySingleton(Context context){
        mCtx = context;
        requestQueue = getRequestQueue();
    }

    public RequestQueue getRequestQueue(){
        if(requestQueue==null){
            requestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
        }
        return requestQueue;
    }

    public static synchronized MySingleton getInstance(Context context){
        if(mInstance==null){
            mInstance = new MySingleton(context);
        }
        return mInstance;
    }

    public void addToRequestQue(Request request){
        requestQueue.add(request);
    }
}

NOTE: The url which will be requested using mySingleton is JsonObjectRequest  and jsonobjectrequest must have a url with api So the url must be something like this baseUrl+city+API key.

Copy these in MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {

    Button button;
    EditText city;
    TextView result;

    //http://api.openweathermap.org/data/2.5/weather?q=Paris&appid=5f56d525d1619d0a2cd2eac4ce55588e

    String baseURL = "http://api.openweathermap.org/data/2.5/weather?q=";
    String API = "&appid=5f56d525d1619d0a2cd2eac4ce55588e";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button);
        city = (EditText) findViewById(R.id.getCity);
        result = (TextView) findViewById(R.id.result);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String myURL = baseURL + city.getText().toString() + API;
                //Log.i("URL", "URL: " + myURL);

                JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, myURL, null,
                        new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject jsonObject) {
                                Log.i("JSON", "JSON: " + jsonObject);

                                try {
                                    String info = jsonObject.getString("weather");
                                    Log.i("INFO", "INFO: "+ info);

                                    JSONArray ar = new JSONArray(info);

                                    for (int i = 0; i < ar.length(); i++){
                                        JSONObject parObj = ar.getJSONObject(i);

                                        String myWeather = parObj.getString("main");
                                        result.setText(myWeather);
                                        Log.i("ID", "ID: " + parObj.getString("id"));
                                        Log.i("MAIN", "MAIN: " + parObj.getString("main"));
                                    }


                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }




                            }
                        },

                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError volleyError) {
                                Log.i("Error", "Something went wrong" + volleyError);

                            }
                        }


                );
                MySingleton.getInstance(MainActivity.this).addToRequestQue(jsonObjectRequest);

            }
        });
    }
}

Lets see what is exactly happening in the MainActivity.java

  • First we set the base url from where we want to fetch the data and API key of your registered one.
  • Then when a user enters a city name ,an url is set up as to request (GET) and get the JSON data from the url by using JsonObjectRequest ,this returns the data inn JSON Onject format something just like this,

JSON: {“coord”:{“lon”:2.35,”lat”:48.86},”weather”:[{“id”:801,”main”:”Clouds”,”description”:”few clouds”,”icon”:”02d”}],”base”:”stations”,”main”:{“temp”:283.58,”pressure”:1034,”humidity”:77,”temp_min”:282.15,”temp_max”:285.93},”visibility”:10000,”wind”:{“speed”:2.6},”clouds”:{“all”:20},”dt”:1553599943,”sys”:{“type”:1,”id”:6540,”message”:0.0052,”country”:”FR”,”sunrise”:1553578899,”sunset”:1553623857},”id”:2988507,”name”:”Paris”,”cod”:200}

  • We take the necessary data which we want and leave other. In this e xample app we take only the main inside of weather Array of objects.
  • Finally we request the volley to get the data from the server. This is achieved by using,
MySingleton.getInstance(MainActivity.this).addToRequestQue(jsonObjectRequest);

The app would have an output like this,

Thank you for reading this post. Follow us on Instagram and Facebook.


To know more tips and tricks you can follow articles on this category :
https://blog.hiewpoint.com/off-topic/

To know about web development and WordPress follow
https://blog.hiewpoint.com/web/

To know about Android development and Android Studio follow
https://blog.hiewpoint.com/android/