Android Login using API Example

Android Login UI/UX design with API Integration Tutorial:-

Tools I will be using:-

  1. Android Studio
  2. JSON blob
  3. Postman
  4. Volley Networking Library
  5. Gson - a Java library

Things you will be learning today:

  • Android UI design fundamentals with basic idea of Material Design.
  • How to do validation.
  • How to create an Mock API in JSON blob.
  • How to use Postman to test API
  • How to create models.
  • How to store login credentials using Shared Preferences.
  • Going to next Activity with onClick of a Login button.
About My Environment: Am using Microsoft windows 10 operating system.

Quick Introduction to the tools I will be using:-

1. Android Studio:-

  The Android Studio developer team says "Android Studio provides the fastest tools for building apps on every type of Android device. World-class code editing, debugging, performance tooling, a flexible build system, and an instant build/deploy system all allow you to focus on building unique and high quality apps."

I strongly recommend you to download Android studio(click here), if you don't have it yet. There are no other IDE. You may say Eclipse-ADT but the last update for this plugin was on March 2015. The Eclipse-ADT plugin is DEPRECATED. For more information about Eclipse-ADT plugin updates click here.

2. JSON blob:-

   The JSON blob developer team says "JSON Blob was created to help parallelize client/server development. Mock JSON responses can be defined using the online editor and then clients can use the JSON Blob API to retrieve and update the mock responses."

Hats-off to the developer's for their smart work. I will be using this tool to create mock API's. To visit their website click here.

3. Postman:-

  The Postman developer team says "Postman is the essential tool chain for API developers to share, test, document and monitor APIs. More than 3 million engineers and developers worldwide use Postman to build connected software via APIs—quickly, easily and accurately. Postman's free Mac, Windows, Linux and Chrome apps, along with Postman's paid Pro and Enterprise offerings, are standards at industry leading businesses. Postman has offices in San Francisco, Bangalore, and Austin, and is privately held, with funding from Nexus Venture Partners."

Please download Postman(click here). You can download postman as chrome extension. Using this you can test whether your API is working or not.

4. Volley Networking Library:-

    Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster. Yes, it is faster compared to AsyncTask. It is very easy to learn too. 

5. Gson - Java Library:-

  From official website:   "Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of. There are a few open-source projects that can convert Java objects to JSON. However, most of them require that you place Java annotations in your classes something that you can not do if you do not have access to the source-code. Most also do not fully support the use of Java Generics. Gson considers both of these as very important design goals."

By the End of this session, you can say you are an Android developer-beginner++ 😉.

Task-01: Lets, create a simple test API in JSON blob.

Now go to JSON blob online, click on New and create new json object with two key/value pair. Like shown below:-

{
  "username": "Admin",
  "password": "password1234"

In JSON data, inside curly braces {}, we call it an Object, and data within square brackets we call it an Array. No need to use an array here, all we need is an Object. As you see above, i have created an Object with two Key-Value pairs. 

Important Note:- Key i.e, left side of the colon should be string, and only String. But the Value i.e, right side of the colon can be a string , or can be an integer or an array of integers,  or a Boolean value.

Now, once you have created an JSON Object, click on Save button. And Please copy the link that you see in the address bar.

Task-02:Lets, test the API in Postman

Go to postman, if you have downloaded google chrome extension, simply go to google chrome extensions and run the app, or if you have downloaded the windows application, double click on the postman to open it. Once you have opened the application, paste the address you have copied from JSON blob, and add api/ after .com/   Something like this,

                       My test API from JSON blob is
                       https://jsonblob.com/038319dd-1506-11e7-a0ba-8bbb38d85dbb


                      Now i will add this address in Postman as
                      https://jsonblob.com/api/038319dd-1506-11e7-a0ba-8bbb38d85dbb

Note: Don't copy the above address, it will not work for you. Its ok to be Lazy, but get your work done by yourself. 😇😎

Make sure you have selected GET request and no auth and view as JSON data. Something like this as shown in below image.



Observe carefully on the fields that i have tick marked. Once this is done click Send and you will see the JSON object with status 200 OK. Here Usually while testing any kind of API, developers most of the time use 200 OK as a significance to successful result. But status code depends on the developers, so please read the API documentation carefully before testing it.

Task-03:Lets, create the project

Now, open the Android Studio. Create a new project, give it a name, select the type of app(initially phone and tablet already selected, leave it as it is) and min SDK and select an Empty activity  then click finish.

Once the gradle build is done, its time to time to add depency for volley library for that, on the left side panel in your android studio select Android and in Gradle Scripts select build.gradle(Module:app) and copy the below volley dependency and paste it below other dependencies you will see at the bottom of the page.


Volley dependency: compile 'com.android.volley:volley:1.0.0'
  Gson dependency: compile 'com.google.code.gson:gson:2.8.0'

Once this is done build the project again by clicking on sync now. Once the build is finished you have to add INTERNET PERMISSION to your application. You can do this by going to Manifest file add the below line of code above the application tag,

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

Task-04:Lets, design User Interface

  • MainActivity.java----This is the main activity
  • Main2Activity.java---This is the second activity
  • KeyValuePair.java---This is a model
  • activity_main.xml
  • activty_main2.xml
Let the strings.xml and colors.xml  and styles.xml be as it is. Now open activity_main.xml
You can find it in res folder under layouts.

Add the following Code: to activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
    tools:context="basavaraj.androidtutorialsamples.com.androidloginapi.MainActivity">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingRight="16dp"
        android:paddingLeft="16dp">

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">
              <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:orientation="vertical">

                <android.support.design.widget.TextInputLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:paddingBottom="16dp">

                    <EditText
                        android:id="@+id/et_username"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:hint="Username"
                        android:paddingLeft="5dp"
                        android:paddingRight="5dp"
                        android:singleLine="true"/>
                </android.support.design.widget.TextInputLayout>
                <android.support.design.widget.TextInputLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:paddingBottom="16dp">

                    <EditText
                        android:id="@+id/et_password"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:hint="Password"
                        android:paddingLeft="5dp"
                        android:paddingRight="5dp"
                        android:inputType="textWebPassword"
                        android:singleLine="true"/>
                </android.support.design.widget.TextInputLayout>
                <Button
                    android:id="@+id/bt_Login"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/login"
                    android:background="@color/colorPrimary"/>
            </LinearLayout>
        </ScrollView>
    </RelativeLayout>
Now in activty_main2.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context="basavaraj.androidtutorialsamples.com.androidloginapi.Main2Activity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Thank you!, would love to hear it from you."
            android:layout_marginBottom="16dp"
            android:textSize="18sp"/>

        <ImageView
            android:layout_width="75dp"
            android:layout_height="75dp"
            android:src="@drawable/ic_sentiment_satisfied_black_24dp"/>

        <Button
            android:id="@+id/bt_logout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="logout"
            android:layout_marginTop="16dp"
            android:background="@color/colorPrimary" />
    </LinearLayout>
</RelativeLayout>
Below is the code in KeyValuePair.java:
package basavaraj.androidtutorialsamples.com.androidloginapi.model;
/**
 * Created by Basavaraju on 3/31/2017.
 */
public class KeyValuePair {
    private String Key;
    private String Value;

    public KeyValuePair(){
        Key="";
        Value="";
    }

    public KeyValuePair(String key, String value) {
        Key = key;
        Value = value;
    }

    public String getKey() {
        return Key;
    }

    public void setKey(String key) {
        Key = key;
    }

    public String getValue() {
        return Value;
    }

    public void setValue(String value) {
        Value = value;
    }
}
Below is the code in MainActivity.java:
package basavaraj.androidtutorialsamples.com.androidloginapi;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.NoConnectionError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;

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

import java.util.ArrayList;

import basavaraj.androidtutorialsamples.com.androidloginapi.model.KeyValuePair;

public class MainActivity extends AppCompatActivity {

    Button bt_login;
    EditText et_username, et_password;
    Gson gson;
    SharedPreferences sharedPreferences;
    String URL = "https://jsonblob.com/api/038319dd-1506-11e7-a0ba-8bbb38d85dbb";

    public static final String Sp_Status = "Status";
    public static final String MyPref = "MyPref";
    static int mStatusCode = 0;
    public String username, password;
    private Boolean exit = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_username = (EditText) findViewById(R.id.et_username);
        et_password = (EditText) findViewById(R.id.et_password);
        bt_login = (Button) findViewById(R.id.bt_Login);
        OnClick();
        sharedPreferences = getSharedPreferences(MyPref, Context.MODE_PRIVATE);
        if (sharedPreferences.getString(MainActivity.Sp_Status,"").matches("LoggedIn")){
            startActivity(new Intent(MainActivity.this, Main2Activity.class));
        }

    }

    private void OnClick() {
        bt_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                username = et_username.getText().toString().trim();
                password = et_password.getText().toString().trim();
                if (username.length() >= 1) {
                    if (password.length() >= 1) {
                        loginapi();
                    } else {
                        et_password.setError("Please enter Password");
                    }
                } else {
                    et_username.setError("Please enter Username");
                }

            }
        });
    }

    @Override
    public void onBackPressed() {
        if (exit) {
            finish(); // finish activity
        } else {
            Toast.makeText(this, "Press Back again to Exit.",
                    Toast.LENGTH_SHORT).show();
            exit = true;
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    exit = false;
                }
            }, 3 * 1000);
        }
    }

    private void loginapi() {
        ArrayList params = new ArrayList();
        params.add(new KeyValuePair("UserName", username));
        params.add(new KeyValuePair("Password", password));
        RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL,
                new Response.Listener() {
                    @Override
                    public void onResponse(String response) {
                       sharedPreferences = getSharedPreferences(MyPref, Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        gson = new Gson();
                        switch (mStatusCode) {
                            case 200:
                                try {
                                    JSONObject jsonObject = new JSONObject(response);
                                    gson.fromJson(jsonObject.toString(), KeyValuePair.class);
                                    Toast.makeText(MainActivity.this, "Login Successful", Toast.LENGTH_SHORT).show();
                                    editor.putString(Sp_Status, "LoggedIn");
                                    editor.commit();
                                    startActivity(new Intent(MainActivity.this, Main2Activity.class));
                                    finish();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                        }
                    }
                }
                , new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                    Toast.makeText(MainActivity.this, "Server Down", Toast.LENGTH_SHORT).show();
                }
            }
        }) {
            @Override
            protected Response parseNetworkResponse(NetworkResponse response) {
                mStatusCode = response.statusCode;
                return super.parseNetworkResponse(response);
            }
        };
        stringRequest.setRetryPolicy(new
                DefaultRetryPolicy(3000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)
        );
        requestQueue.add(stringRequest);
    }
}
Below is the code for Main2Activity.java:
package basavaraj.androidtutorialsamples.com.androidloginapi;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class Main2Activity extends AppCompatActivity {

    Button bt_logout;
    SharedPreferences sharedPreferences;
    public static final String MyPref = "MyPref";
    private Boolean exit = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        bt_logout = (Button) findViewById(R.id.bt_logout);
        OnClick();
    }

    private void OnClick() {
        bt_logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sharedPreferences = getSharedPreferences(MyPref, Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.clear();
                editor.commit();
                finish();
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (exit) {
            finish();
        } else {
            Toast.makeText(this, "Press Back again to Exit.",
                    Toast.LENGTH_SHORT).show();
            exit = true;
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    exit = false;
                }
            }, 3 * 1000);
        }

    }
}

Now you're done. Go and compile. If you want to know the flow of the code, attach a debugger.

You can get the whole project here. Download

PS: Go ahead and add the random credentials for the login, and it will work. Why?, because we are using JSON blob, it sends the response irrespective of the credentials.

Hope you have learned a bit today. If any doubts or facing issues with my code, please feel free to ask me in the comment section. 

Thank you.😄😊

Comments

  1. Top 10 betting sites for Sports toto in 2021
    The ultimate list of sports betting sites in the USA. If you are looking for 토토사이트 the best sportsbook for football and basketball, you'll want to try

    ReplyDelete
  2. Play Cafe Cafe - Cafe Casino & Brewery | Mapyro
    Cafe 군산 출장샵 Cafe is 안성 출장마사지 an American-inspired restaurant located in Tuscany. It is located in the 이천 출장샵 Tuscany Casino 여주 출장샵 and in the 전주 출장마사지 Wine Garden area.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete

Post a Comment