Alamat

Jl. Jatirejo No 29A, Jatirejo RT 02/21, Sendangadi, Mlati, Sleman, Daerah Istimewa Yogyakarta

Senin - Jum'at (09:00-17:00 WIB)

0878-2877-3103

0878-2877-3103

Membuat Aplikasi Login Android Dengan SQLite Database

Farid Efendi
  • 17 Jan 2021
  • 19 menit dibaca
Membuat Aplikasi Login Android Dengan SQLite Database

Ada beberapa aplikasi Android yang membutuhkan authentikasi sebelum masuk ke halaman utama. Authentikasi berguna untuk mengenali siapa yang akan menggunakan aplikasi serta apa saja hak aksesnya. Apa saja contohnya?, aplikasi mobile banking, inventory, bahkan aplikasi tagihan internet juga perlu authentikasi login untuk mengenali pemakainya.

Uraian kali ini bercerita tentang cara membuat aplikasi login sederhana dengan bantuan database SQLite. Sederhananya nanti ketika user membuka aplikasi maka akan ada pengecekan apakah sudah terdeteksi siapa penggunanya sebelum masuk ke halaman utama, jika belum terdeteksi maka user diwajibkan untuk mengisi email serta passwordnya. Bagaimana jika user belum memiliki akun di aplikasi?, disediakan form khusus untuk mendaftarkan akun baru yang akan tersimpan di database SQLite. 

Langkah pertama yang wajib diperlukan adalah persiapkan Android Studio. Harus Android Studio?, Boleh juga menggunakan aplikasi lainnya seperti Eclipse, namun karena tutorial kali ini bernarasi dengan Android Studio maka akan lebih mudah dipahami jika memakai Android Studio.

Buat Project Baru

Buatlah project baru dengan nama "Tutorial Login Sederhana". Caranya buka menu File -> New -> New Project hingga muncul form berikut :

Form buat project baru

Isilah kolom Application Name dan Company Domain lalu klik tombol Next untuk melanjutkan proses ke pilihan Target Device

Klik tombol Next dan selanjutnya pilih "Empty Activity" untuk membuat aktifitas kosong di project ini.

Secara default akan terisi nama aktifitas "MainActivity" di form selanjutnya. Gunakan saja nama default tersebut lalu klik tombol "Finish".

Tunggulah hingga proses selesai.

Persiapkan Resource String, Dimens, dan Colors

File - file resource berada di dalam folder app -> src -> main ->res ->values. Normalnya sudah ada 3 file colors.xml, strings.xml, styles.xml. File colors.xml untuk menyimpan variable warna, strings.xml berisi variable semua text, dan styles.xml untuk menampung variable untuk konfigurasi tema.
Tambahkan beberapa variable di file colors dan strings sehingga isinya masing - masing jadi seperti berikut :

colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
    <color name="colorRed">#e13d5f</color>
    <color name="colorGrey">#ebebeb</color>
    <color name="colorWhite">#ffffff</color>

    <color name="alertPrimary">#cce5ff</color>
    <color name="alertPrimaryFontColor">#004085</color>
    <color name="alertSuccess">#d4edda</color>
    <color name="alertSuccessFontColor">#155724</color>
    <color name="alertDanger">#f8d7da</color>
    <color name="alertDangerFontColor">#721c24</color>
    <color name="alertWarning">#fff3cd</color>
    <color name="alertWarningFontColor">#856404</color>
    <color name="alertInfo">#d1ecf1</color>
    <color name="alertInfoFontColor">#0c5460</color>
    <color name="alertSecondary">#e2e3e5</color>
    <color name="alertSecondaryFontColor">#383d41</color>

    <color name="btnPrimary">#007bff</color>
    <color name="btnSecondary">#6c757d</color>
    <color name="btnSuccess">#28a745</color>
    <color name="btnDanger">#dc3545</color>
    <color name="btnWarning">#ffc107</color>
    <color name="btnInfo">#17a2b8</color>

</resources>

strings.xml

<resources>
    <string name="app_name">Tutorial Login Sederhana</string>

    <string name="title_activity_login">Sign in or create an account</string>
    <string name="title_activity_main">Dashboard</string>

    <string name="prompt_email">Email</string>
    <string name="prompt_password">Password</string>
    <string name="prompt_password_repeat">Password (Diulang)</string>
    <string name="prompt_name">Nama Lengkap</string>
    <string name="prompt_phone">Nomor Telepon</string>
    <string name="action_sign_in">Masuk atau Mendaftar</string>
    <string name="action_sign_in_short">Masuk</string>
    <string name="action_register">Buat akun baru?</string>
    <string name="action_have_account">Sudah memiliki akun?</string>
    <string name="action_submit">Kirim</string>
    <string name="error_invalid_email">Alamat email tidak valid</string>
    <string name="error_unavailable_email">Email sudah pernah terdaftar</string>
    <string name="error_invalid_password">Password tidak valid</string>
    <string name="error_invalid_password_repeat">Ulangi password dengan benar</string>
    <string name="error_incorrect_password">Password yang Anda masukkan salah</string>
    <string name="error_old_password">Password lama salah</string>
    <string name="error_field_required">Kolom ini tidak boleh dikosongi</string>
    <string name="permission_rationale">"Izin kontak diperlukan untuk menyediakan penyelesaian email."</string>
    <string name="login_header_information">Isilah form ini dengan akun login anda,
        atau buat akun terlebih dahulu untuk dapat menggunakan aplikasi ini.</string>

    <string name="txt_welcome">Selamat datang</string>

    <string name="btn_logout">Logout</string>
</resources>

Tambahkan 1 file resource dalam folder yang sama dengan file di atas dengan nama file dimens.xml untuk menampung varible dimensi atau ukuran margin, padding, dan lain - lain.

dimens.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
</resources>

Variable yang sudah kita buat ini sangat berguna untuk menghindari hardcode di dalam penulisan code. Apalagi variable strings nantinya sangat penting jika ingin membangun aplikasi multi language, tinggal menambahkan file strings.xml di folder lain untuk support bahasa yang lainnya. Cukup sekali panggil @string/nama_variable akan dikembalikan nilai variable tersebut sesuai dengan bahasa yang sudah terkonfigurasi.

Persiapkan Database dan Beberapa Utility-nya

Data user untuk pengecekan authentikasi akan disimpan dalam database SQLite. Android sudah menyediakan class untuk berinteraksi dengan database yakni SQLiteOpenHelper. Buatlah folder baru atau Package dengan nama utils di dalam folder app -> src -> main -> java -> com -> slightsite -> tutorialloginsederhana . Lebih mudah buat folder tersebut di Android Studio cukup dengan klik kanan folder com.slightsite.tutorialloginsederhana lalu pilih New -> Package dan beri nama "utils". Setelah folder atau package terbuat lalu buat 3 file dalam folder tersebut yakni Database.java, DatabaseContents.java, dan DatabaseHelper.java. Struktur filenya seharusnya seperti ini:

Database.java

package com.slightsite.tutorialloginsederhana.utils;

import java.util.List;

public interface Database {

    /**
     * Selects something in database.
     * @param queryString query string for select in database.
     * @return list of object.
     */
    public List<Object> select(String queryString);

    /**
     * Inserts something in database.
     * @param tableName name of table in database.
     * @param content string for using in database.
     * @return id of row data.
     */
    public int insert(String tableName, Object content);

    /**
     * Updates something in database.
     * @param tableName name of table in database.
     * @param content string for using in database.
     * @return true if updates success ; otherwise false.
     */
    boolean update(String tableName, Object content);

    /**
     * Deletes something in database.
     * @param tableName name of table in database.
     * @param id a specific id of row data for deletion.
     * @return true if deletion success ; otherwise false.
     */
    boolean delete(String tableName, int id);

    /**
     * Directly execute to database.
     * @param queryString query string for execute.
     * @return true if executes success ; otherwise false.
     */
    boolean execute(String queryString);
}

Class Database berisi default method untuk membaca, menyimpan, mengubah, dan menghapus data.

DatabaseContents.java

package com.slightsite.tutorialloginsederhana.utils;

public enum DatabaseContents {

    DATABASE("loginsederhana.db"),
    TABLE_USERS("tbl_users");

    private String name;

    /**
     * Constructs DatabaseContents.
     * @param name name of this content for using in database.
     */
    private DatabaseContents(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }
}

Class DatabaseContents ini berguna untuk mendefinisikan nama database serta nama tabel - tabelnya.

DatabaseHelper.java

package com.slightsite.tutorialloginsederhana.utils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

public class DatabaseHelper extends SQLiteOpenHelper implements Database {

    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = DatabaseContents.DATABASE.toString();


    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL("CREATE TABLE " + DatabaseContents.TABLE_USERS + "("
                + "_id INTEGER PRIMARY KEY,"
                + "name TEXT(100),"
                + "email TEXT(32),"
                + "password TEXT(256),"
                + "phone TEXT(32),"
                + "status INTEGER DEFAULT 1,"
                + "date_added DATETIME"
                + ");");

        Log.d("CREATE DATABASE", "Create " + DatabaseContents.TABLE_USERS + " Successfully.");
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + DatabaseContents.TABLE_USERS);

        // Create tables again
        onCreate(db);
    }

    @Override
    public List<Object> select(String queryString) {
        try {
            SQLiteDatabase database = this.getWritableDatabase();
            List<Object> list = new ArrayList<Object>();
            Cursor cursor = database.rawQuery(queryString, null);

            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    do {
                        ContentValues content = new ContentValues();
                        String[] columnNames = cursor.getColumnNames();
                        for (String columnName : columnNames) {
                            content.put(columnName, cursor.getString(cursor
                                    .getColumnIndex(columnName)));
                        }
                        list.add(content);
                    } while (cursor.moveToNext());
                }
            }
            cursor.close();
            database.close();
            return list;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public int insert(String tableName, Object content) {
        try {
            SQLiteDatabase database = this.getWritableDatabase();

            int id = (int) database.insert(tableName, null,
                    (ContentValues) content);

            database.close();
            return id;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    @Override
    public boolean update(String tableName, Object content) {
        try {
            SQLiteDatabase database = this.getWritableDatabase();
            ContentValues cont = (ContentValues) content;
            // this array will always contains only one element.
            String[] array = new String[]{cont.get("_id")+""};
            database.update(tableName, cont, " _id = ?", array);
            return true;

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean delete(String tableName, int id) {
        try {
            SQLiteDatabase database = this.getWritableDatabase();
            database.delete(tableName, " _id = ?", new String[]{id+""});
            return true;

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean execute(String queryString) {
        try{
            SQLiteDatabase database = this.getWritableDatabase();
            database.execSQL(queryString);
            return true;
        }catch(Exception e){
            e.printStackTrace();
            return false;
        }
    }
}

DatabaseHelper inilah yang akan selalu dipanggil untuk berinteraksi dengan tabel tertentu di dalam database baik untuk mengambil data, membuat data baru, mengubah, serta menghapus data.

Buat Controller Sebagai Alat Komunikasi Antara Activity dengan Database

Berbagai urusan yang berkaitan dengan View atau antarmuka yang nampak oleh pengguna akan dikelola di dalam class Activity. Jika Activity ingin berinteraksi dengan database maka untuk lebih mudah dan rapi kita gunakan Controller. Gunakan prosedur yang sama dengan membuat class untuk database di atas. Buat folder atau package baru dengan nama "controllers" di dalam folder app -> src -> main -> java -> com -> slightsite -> tutorialloginsederhana dan ciptakan class baru dengan nama "UserController" di file UserController.java. Struktur file dan folder menjadi :

UserController.java

package com.slightsite.tutorialloginsederhana.controllers;

import android.content.ContentValues;

import com.slightsite.tutorialloginsederhana.utils.Database;
import com.slightsite.tutorialloginsederhana.utils.DatabaseContents;

import java.util.List;

public class UserController {
    private static Database database;
    private static UserController instance;

    private UserController() {}

    public static UserController getInstance() {
        if (instance == null)
            instance = new UserController();

        return instance;
    }

    /**
     * Sets database for use in this class.
     * @param db database.
     */
    public static void setDatabase(Database db) {
        database = db;
    }

    public ContentValues getDataByEmail(String email) {
        String queryString = "SELECT * FROM " + DatabaseContents.TABLE_USERS + " WHERE email = '"+ email +"'";
        List<Object> contents = database.select(queryString);

        if (contents.isEmpty()) {
            return null;
        }

        ContentValues content = (ContentValues) contents.get(0);
        return content;
    }

    public Object getUsers() {
        List<Object> contents = database.select("SELECT * FROM " + DatabaseContents.TABLE_USERS);

        return contents;
    }

    public int register(ContentValues content) {
        int id = database.insert(DatabaseContents.TABLE_USERS.toString(), content);

        return id;
    }

    public boolean update(ContentValues content) {
        boolean update = database.update(DatabaseContents.TABLE_USERS.toString(), content);

        return update;
    }
}

Siapkan Form Login dan Registrasi Akun Baru

Inilah saatnya membuat form login dan form registrasi akun baru untuk pengguna. Caranya buat activity baru dengan nama "LoginActivty". Klik kanan folder com.slightsite.tutorialloginsederhana di dalam folder java, pilih New -> Java Class hingga muncul form berikut :

Buat juga file activity_login.xml di folder res -> layout. Cara lainnya yang lebih mudah agar file LoginActivity.java dan activity_login.xml tergenerate secara otomatis adalah dengan klik kanan folder com.slightsite.tutorialloginsederhana di dalam folder java lalu pilih New -> Activity -> Basic Activity . Jika berhasil, maka akan ada 2 file baru di dalam folder berikut :

Update isi dari 2 file (LoginActivity.java dan activity_login.xml) tersebut sehingga isinya menjadi :

LoginActivity.java

package com.slightsite.tutorialloginsederhana;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.slightsite.tutorialloginsederhana.controllers.UserController;
import com.slightsite.tutorialloginsederhana.utils.Database;
import com.slightsite.tutorialloginsederhana.utils.DatabaseHelper;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class LoginActivity extends AppCompatActivity {

    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    private UserLoginTask mAuthTask = null;

    // UI references.
    private EditText mEmailView;
    private EditText mPasswordView;
    private EditText passwordRepeat;
    private EditText nameBox;
    private EditText phoneBox;
    private Button mEmailSignInButton;
    private Button signup_button;
    private Button register_button;
    private Button signin_button;
    private View mProgressView;
    private View mLoginFormView;

    public final static String TAG_ID = "id";
    public final static String TAG_EMAIL = "email";
    public final static String TAG_NAME = "name";
    public final static String TAG_PHONE = "phone";
    public final static String TAG_PASSWORD = "password";

    SharedPreferences sharedpreferences;
    Boolean session = false;
    String id, email, name;
    public static final String my_shared_preferences = "my_shared_preferences";
    public static final String session_status = "session_status";

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

        initiateCoreApp();
        checkSession();

        // Set up the login form.
        mEmailView = (EditText) findViewById(R.id.email);

        mPasswordView = (EditText) findViewById(R.id.password);
        mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });

        mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
        mEmailSignInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });

        mLoginFormView = findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);
        nameBox = findViewById(R.id.nameBox);
        phoneBox = findViewById(R.id.phoneBox);

        signup_button = (Button) findViewById(R.id.signup_button);
        signup_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptRegister();
            }
        });
        register_button = (Button) findViewById(R.id.register_button);
        signin_button = (Button) findViewById(R.id.signin_button);
        passwordRepeat = (EditText) findViewById(R.id.passwordRepeat);
    }

    private void initiateCoreApp() {
        Database database = new DatabaseHelper(this);
        UserController.setDatabase(database);
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {
        if (mAuthTask != null) {
            return;
        }

        // Reset errors.
        mEmailView.setError(null);
        mPasswordView.setError(null);

        // Store values at the time of the login attempt.
        String email = mEmailView.getText().toString();
        String password = mPasswordView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid password, if the user entered one.
        if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = true;
        }

        // Check for a valid email address.
        if (TextUtils.isEmpty(email)) {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        } else if (!isEmailValid(email)) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = true;
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            showProgress(true);
            mAuthTask = new UserLoginTask(email, password);
            mAuthTask.execute((Void) null);
        }
    }

    public static boolean isEmailValid(String email) {
        //TODO: Replace this with your own logic
        return email.contains("@");
    }

    public static boolean isPasswordValid(String password) {
        //TODO: Replace this with your own logic
        return password.length() > 2;
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime).alpha(
                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });

            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(
                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {

        private final String mEmail;
        private final String mPassword;
        private ContentValues admin;

        UserLoginTask(String email, String password) {
            mEmail = email;
            mPassword = password;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.
            admin = UserController.getInstance().getDataByEmail(mEmail);
            if (admin != null) {
                if (mPassword.equals(admin.getAsString("password"))) {
                    SharedPreferences.Editor editor = sharedpreferences.edit();
                    editor.putBoolean(session_status, true);
                    editor.putString(TAG_ID, admin.getAsString("_id"));
                    editor.putString(TAG_EMAIL, admin.getAsString("email"));
                    editor.putString(TAG_NAME, admin.getAsString("name"));
                    editor.putString(TAG_PHONE, admin.getAsString("phone"));
                    editor.commit();
                } else {
                    return false;
                }

                return true;
            }

            return false;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            showProgress(false);

            if (success) {
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                intent.putExtra(TAG_ID, id);
                intent.putExtra(TAG_EMAIL, email);
                if (admin != null) {
                    intent.putExtra(TAG_NAME, admin.getAsString("name"));
                }
                finish();
                startActivity(intent);
            } else {
                mPasswordView.setError(getString(R.string.error_incorrect_password));
                mPasswordView.requestFocus();
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }

    private void checkSession() {
        sharedpreferences = getSharedPreferences(my_shared_preferences, Context.MODE_PRIVATE);
        session = sharedpreferences.getBoolean(session_status, false);
        id = sharedpreferences.getString(TAG_ID, null);
        email = sharedpreferences.getString(TAG_EMAIL, null);
        name = sharedpreferences.getString(TAG_NAME, null);

        if (session) {
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            intent.putExtra(TAG_ID, id);
            intent.putExtra(TAG_EMAIL, email);
            intent.putExtra(TAG_NAME, name);
            finish();
            startActivity(intent);
        }
    }

    public void registerRequest(View view) {
        nameBox.setVisibility(View.VISIBLE);
        phoneBox.setVisibility(View.VISIBLE);
        mEmailSignInButton.setVisibility(View.GONE);
        signup_button.setVisibility(View.VISIBLE);
        register_button.setVisibility(View.GONE);
        signin_button.setVisibility(View.VISIBLE);
        passwordRepeat.setVisibility(View.VISIBLE);
    }

    public void signinRequest(View view) {
        nameBox.setVisibility(View.GONE);
        phoneBox.setVisibility(View.GONE);
        mEmailSignInButton.setVisibility(View.VISIBLE);
        signup_button.setVisibility(View.GONE);
        register_button.setVisibility(View.VISIBLE);
        signin_button.setVisibility(View.GONE);
        passwordRepeat.setVisibility(View.GONE);
    }

    private void attemptRegister() {
        if (mAuthTask != null) {
            return;
        }

        // Reset errors.
        mEmailView.setError(null);
        mPasswordView.setError(null);

        // Store values at the time of the login attempt.
        String email = mEmailView.getText().toString();
        String password = mPasswordView.getText().toString();
        String password_repeat = passwordRepeat.getText().toString();
        String full_name = nameBox.getText().toString();
        String phone = phoneBox.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid password, if the user entered one.
        if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = true;
        }

        if (!TextUtils.isEmpty(password_repeat) && !isPasswordValid(password_repeat)) {
            passwordRepeat.setError(getString(R.string.error_invalid_password));
            focusView = passwordRepeat;
            cancel = true;
        }

        if (!password_repeat.equals(password)) {
            passwordRepeat.setError(getString(R.string.error_invalid_password_repeat));
            focusView = passwordRepeat;
            cancel = true;
        }

        // Check for a valid email address.
        if (TextUtils.isEmpty(email)) {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        } else if (!isEmailValid(email)) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = true;
        } else {
            ContentValues adminData = UserController.getInstance().getDataByEmail(email);
            if (adminData != null) {
                mEmailView.setError(getString(R.string.error_unavailable_email));
                focusView = mEmailView;
                cancel = true;
            }
        }

        if (TextUtils.isEmpty(full_name)) {
            nameBox.setError(getString(R.string.error_field_required));
            focusView = nameBox;
            cancel = true;
        }

        if (TextUtils.isEmpty(phone)) {
            phoneBox.setError(getString(R.string.error_field_required));
            focusView = phoneBox;
            cancel = true;
        }

        if (cancel) {
            focusView.requestFocus();
        } else {
            showProgress(true);

            ContentValues content = new ContentValues();
            content.put("email", email);
            content.put("name", full_name);
            content.put("password", password);
            content.put("phone", phone);
            content.put("date_added", getCurrentTime());

            int id = UserController.getInstance().register(content);
            if (id > 0) {
                mAuthTask = new UserLoginTask(email, password);
                mAuthTask.execute((Void) null);
            }
        }
    }

    /**
     * Geting current time
     * @return
     */
    private String getCurrentTime() {
        Date c = Calendar.getInstance().getTime();

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedDate = df.format(c);
        
        return formattedDate;
    }
}

activity_login.xml

<?xml version="1.0" encoding="utf-8"?>
<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:gravity="center_horizontal"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".LoginActivity">

    <!-- Login progress -->
    <ProgressBar
        android:id="@+id/login_progress"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:visibility="gone" />

    <ScrollView
        android:id="@+id/login_form"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:id="@+id/email_login_form"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_below="@+id/logo_container">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textStyle="bold"
                android:textAllCaps="false"
                android:text="@string/login_header_information"
                android:layout_marginVertical="10dp"
                android:padding="8dp"
                android:background="@color/alertInfo"
                android:textColor="@color/alertInfoFontColor"/>

            <EditText
                android:id="@+id/email"
                style="?android:textAppearanceSmall"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/prompt_email"
                android:inputType="textEmailAddress"
                android:maxLines="1"
                android:singleLine="true" />

            <EditText
                android:id="@+id/password"
                style="?android:textAppearanceSmall"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/prompt_password"
                android:imeActionId="6"
                android:imeActionLabel="@string/action_sign_in_short"
                android:imeOptions="actionUnspecified"
                android:inputType="textPassword"
                android:maxLines="1"
                android:singleLine="true" />

            <EditText
                android:id="@+id/passwordRepeat"
                style="?android:textAppearanceSmall"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/prompt_password_repeat"
                android:imeActionId="6"
                android:imeActionLabel="@string/action_sign_in_short"
                android:imeOptions="actionUnspecified"
                android:inputType="textPassword"
                android:maxLines="1"
                android:singleLine="true"
                android:visibility="gone"/>

            <EditText
                android:id="@+id/nameBox"
                style="?android:textAppearanceSmall"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/prompt_name"
                android:imeActionId="6"
                android:imeActionLabel="@string/action_sign_in_short"
                android:imeOptions="actionUnspecified"
                android:inputType="textPersonName"
                android:maxLines="1"
                android:singleLine="true"
                android:visibility="gone"/>

            <EditText
                android:id="@+id/phoneBox"
                style="?android:textAppearanceSmall"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/prompt_phone"
                android:imeActionId="6"
                android:imeActionLabel="@string/action_sign_in_short"
                android:imeOptions="actionUnspecified"
                android:inputType="phone"
                android:maxLines="1"
                android:singleLine="true"
                android:visibility="gone"/>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:weightSum="2">

                <Button
                    android:id="@+id/email_sign_in_button"
                    style="?android:textAppearanceSmall"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="16dp"
                    android:text="@string/action_sign_in_short"
                    android:textStyle="bold"
                    android:layout_weight="1"
                    android:background="@color/btnInfo"
                    android:textColor="@color/colorWhite"/>

                <Button
                    android:id="@+id/register_button"
                    style="?android:textAppearanceSmall"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="16dp"
                    android:text="@string/action_register"
                    android:layout_weight="1"
                    android:background="@android:color/transparent"
                    android:onClick="registerRequest"
                    android:clickable="true"/>

                <Button
                    android:id="@+id/signup_button"
                    style="?android:textAppearanceSmall"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="16dp"
                    android:text="@string/action_submit"
                    android:textStyle="bold"
                    android:layout_weight="0.75"
                    android:visibility="gone"
                    android:background="@color/btnInfo"
                    android:textColor="@color/colorWhite"/>

                <Button
                    android:id="@+id/signin_button"
                    style="?android:textAppearanceSmall"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="16dp"
                    android:text="@string/action_have_account"
                    android:layout_weight="1.25"
                    android:background="@android:color/transparent"
                    android:onClick="signinRequest"
                    android:clickable="true"
                    android:visibility="gone"/>

            </LinearLayout>

        </LinearLayout>
    </ScrollView>
</LinearLayout>

Pastikan LoginActivity sudah terdefinisi di file AndroidManifest.xml agar activity ini dapat digunakan. Letak file tersebut ada di folder app -> src -> main. Jadikan LoginActivity sebagai main intent agar activity ini di eksekusi pertama kali saat aplikasi dibuka.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.slightsite.tutorialloginsederhana">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".LoginActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main"
            android:screenOrientation="portrait" />
    </application>

</manifest>

Siapkan Halaman Utama atau Dashboard Setelah Login

Jika user sukses login atau registrasi maka user akan di lempar ke halaman utama. Kita buatkan halaman dashboard sederhana serta tombol logout untuk menghapus session login.

Update file activity_main.xml dan MainActivity.java dengan code berikut :

activity_main.xml

<?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"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:gravity="center_horizontal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TextView
            android:id="@+id/txt_welcome"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/txt_welcome"
            android:textSize="10pt"
            android:textAllCaps="true"/>

        <TextView
            android:id="@+id/txt_profile_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/txt_welcome"
            android:layout_marginTop="20dp"
            android:text=""
            android:textStyle="bold"
            android:textSize="8pt"
            />

        <Button
            android:id="@+id/btn_logout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/txt_profile_name"
            android:layout_marginTop="30dp"
            android:text="@string/btn_logout"
            android:background="@color/btnWarning"
            android:textColor="@color/colorWhite"
            android:paddingHorizontal="40dp"/>

    </LinearLayout>

</android.support.constraint.ConstraintLayout>

MainActivity.java

package com.slightsite.tutorialloginsederhana;

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

public class MainActivity extends AppCompatActivity {

    TextView txt_profile_name;
    Button btn_logout;

    SharedPreferences sharedpreferences;
    Intent intent;

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

        txt_profile_name = (TextView) findViewById(R.id.txt_profile_name);
        txt_profile_name.setText(getIntent().getExtras().get("name").toString());

        btn_logout = (Button) findViewById(R.id.btn_logout);
        btn_logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                logout();
            }
        });
    }

    private void logout() {
        sharedpreferences = getSharedPreferences(
                LoginActivity.my_shared_preferences, Context.MODE_PRIVATE);

        SharedPreferences.Editor editor = sharedpreferences.edit();
        editor.putBoolean(LoginActivity.session_status, false);
        editor.putString(LoginActivity.TAG_ID, null);
        editor.putString(LoginActivity.TAG_EMAIL, null);
        editor.putString(LoginActivity.TAG_NAME, null);
        editor.putString(LoginActivity.TAG_PHONE, null);
        editor.commit();

        intent = new Intent(MainActivity.this, LoginActivity.class);
        finish();
        startActivity(intent);
    }
}

Akhirnya aplikasi ini siap untuk running, klik menu Run -> Debug 'app' dan pilih emulatornya.

Source code lengkapnya dapat dipelajari di github https://github.com/faridefendi58/tutorial-login atau download secara langsung di sini,  atau download Apk.

Semoga bermanfaat, selamat mencoba!.

Farid Efendi
Farid Efendi

Seneng mempelajari hal baru, gak cuma di Pemrograman, SEO, IM, tapi di luar topik internet juga OK. Biar sakti kayak James Bond.

Tinggalkan Komentar :

bikin website

Ingin belajar membuat website?

Bikin website tuh gak sulit amat, si Amat aja bisa loh bikin website yang bagus dan murah. Mau tau caranya?

Lihat Rahasianya