blog

Home / DeveloperSection / Blogs / Implementation of API in Android

Implementation of API in Android

Prateek sharma 1890 28-Jan-2018

An API is an interface used between the user and the server. There are two types of API’s used which offers a different mechanism for connecting and receiving data. Since connecting an API with an android application requires an internet connection. So make sure that permission is provided in an android manifest file. Write the following in AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>

Create a layout file

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.sample.foo.simplewebapi.MainActivity">
    <EditText
        android:id="@+id/emailText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:hint="Enter email address"/>
    <Button
        android:id="@+id/queryButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end"
        style="@style/Base.Widget.AppCompat.Button.Borderless"
        android:text="Search"/>
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center">
        <ProgressBar
            android:id="@+id/progressBar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:indeterminate="true"
            android:layout_centerHorizontal="true"
            android:visibility="gone" />
        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <TextView
                android:id="@+id/responseView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
        </ScrollView>
    </RelativeLayout>
</LinearLayout>

You need to create the connection with the server in the background thread, so to do that either you can use AsynTask class or any network library. A sample for AsyncTask is given below.

class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
        private Exception exception;
        protected void onPreExecute() {
            progressBar.setVisibility(View.VISIBLE);
            responseView.setText("");
        }
        protected String doInBackground(Void... urls) {
            String email = emailText.getText().toString();
            // Do some validation here
            try {
                URL url = new URL(API_URL + "email=" + email + "&apiKey=" + API_KEY);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                try {
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                    StringBuilder stringBuilder = new StringBuilder();
                    String line;
                    while ((line = bufferedReader.readLine()) != null) {
                        stringBuilder.append(line).append("\n");
                    }
                    bufferedReader.close();
                    return stringBuilder.toString();
                }
                finally{
                    urlConnection.disconnect();
                }
            }
            catch(Exception e) {
                Log.e("ERROR", e.getMessage(), e);
                return null;
            }
        }
        protected void onPostExecute(String response) {
            if(response == null) {
                response = "THERE WAS AN ERROR";
            }
            progressBar.setVisibility(View.GONE);
            Log.i("INFO", response);
            responseView.setText(response);
        }
    }

AsyncTask has three methods onPreExecute(), doInBackground() and onPostExecute().

onPreExecute() is used for some task which need to be considered before making connection such as setting visibility of progress bar etc. onPostExecute() is used for processing after the connection was completed such processing the response etc.



Updated 28-Jan-2018

Leave Comment

Comments

Liked By