Cara Buat Tampilan LOGIN Keren
Dengan Android Studio
Jika sebelumnya kita pernah belajar membuat ui login desain menarik dalam 30 menit menggunakan android studio. Kali ini kita akan belajar membuat form login android pada android studio dengan menggunakan sqlite database.
Untuk aplikasi login sqlite yang sudah running kamu bisa melihatnya pada video dibawah ini.
Membuat Login Android
Tanpa basa basi langsung saja kita praktekan membuat login android menggunakan sqlite database.
1. Buat Project Baru
Langkah pertama silahkan buat project baru di android studio dengan menggunakan nama project loginsqlite. Jika masih bingung kamu bisa membaca tutorial membuat project pertama di android.
2. Library Material Design
Tambahkan library material design dengan cara klik gradle (module:app) > masukan 1 baris kode berikut pada dependencies > klik sync now (pastikan terknoneksi dengan internet )
implementation 'com.android.support:design:26.1.0'
3. Edit String
Edit string yang nantinya digunakan untuk nama aplikasi dan beberapa komponen widget. Buka res > values > string.xml. disini Kamu bisa pelajari struktur folder android .
<resources> <string name="app_name">LoginRegisterScreenDesign</string> <string name="create_account"><font color="#00ff00">text</font></string> <string name="email">Email</string> <string name="password">Password</string> <string name="login">Login</string> <string name="username">Username</string> <string name="register">Register</string> <string name="back_to_login">Back to Login</string> </resources>
4. Edit Color
Edit warna yang dengan cara buka res > values > colors.xml.
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="colorPrimary">#607d8b</color> <color name="colorPrimaryDark">#455a64</color> <color name="colorAccent">#0c0099</color> </resources>
5. Drawable
Copykan gambar/ icon pendukung (download disini ). Caranya klik kanan pada drawable > klik paste.
6. Edit Style
Edit tema pada res > values > styles.xml. Dalam aplikasi yang akan kita buat ini kita tidak akan menampilkan action bar (app bar). Sehingga kode-kodenya kita edit menjadi seperti seperti berikut.
<resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> <style name="AppTheme.NoActionBar"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> </style> <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" /> <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" /> </resources>
7. Activity Login
Buat activity login dengan cara klik folder java > klik kanan nama package > New > Activity > Empty Activity > Isikan Nama LoginActivity. Sehingga akan terdapat class java LoginActivity.java dan layout activity_login.xml.
- LoginActivity.java
Masukan kode-kode berikut dibawah nama package.
import android.content.Intent; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.design.widget.TextInputLayout; import android.support.v7.app.AppCompatActivity; import android.text.Html; import android.text.Spanned; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class LoginActivity extends AppCompatActivity { //Declaration EditTexts EditText editTextEmail; EditText editTextPassword; //Declaration TextInputLayout TextInputLayout textInputLayoutEmail; TextInputLayout textInputLayoutPassword; //Declaration Button Button buttonLogin; //Declaration SqliteHelper SqliteHelper sqliteHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); sqliteHelper = new SqliteHelper(this); initCreateAccountTextView(); initViews(); //set click event of login button buttonLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Check user input is correct or not if (validate()) { //Get values from EditText fields String Email = editTextEmail.getText().toString(); String Password = editTextPassword.getText().toString(); //Authenticate user User currentUser = sqliteHelper.Authenticate(new User(null, null, Email, Password)); //Check Authentication is successful or not if (currentUser != null) { Snackbar.make(buttonLogin, "Successfully Logged in!", Snackbar.LENGTH_LONG).show(); //User Logged in Successfully Launch You home screen activity Intent intent=new Intent(LoginActivity.this,MainActivity.class); startActivity(intent); finish(); } else { //User Logged in Failed Snackbar.make(buttonLogin, "Failed to log in , please try again", Snackbar.LENGTH_LONG).show(); } } } }); } //this method used to set Create account TextView text and click event( maltipal colors // for TextView yet not supported in Xml so i have done it programmatically) private void initCreateAccountTextView() { TextView textViewCreateAccount = (TextView) findViewById(R.id.textViewCreateAccount); textViewCreateAccount.setText(fromHtml("<font color='#ffffff'>I don't have account yet. </font><font color='#0c0099'>create one</font>")); textViewCreateAccount.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(LoginActivity.this, RegisterActivity.class); startActivity(intent); } }); } //this method is used to connect XML views to its Objects private void initViews() { editTextEmail = (EditText) findViewById(R.id.editTextEmail); editTextPassword = (EditText) findViewById(R.id.editTextPassword); textInputLayoutEmail = (TextInputLayout) findViewById(R.id.textInputLayoutEmail); textInputLayoutPassword = (TextInputLayout) findViewById(R.id.textInputLayoutPassword); buttonLogin = (Button) findViewById(R.id.buttonLogin); } //This method is for handling fromHtml method deprecation @SuppressWarnings("deprecation") public static Spanned fromHtml(String html) { Spanned result; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) { result = Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY); } else { result = Html.fromHtml(html); } return result; } //This method is used to validate input given by user public boolean validate() { boolean valid = false; //Get values from EditText fields String Email = editTextEmail.getText().toString(); String Password = editTextPassword.getText().toString(); //Handling validation for Email field if (!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches()) { valid = false; textInputLayoutEmail.setError("Please enter valid email!"); } else { valid = true; textInputLayoutEmail.setError(null); } //Handling validation for Password field if (Password.isEmpty()) { valid = false; textInputLayoutPassword.setError("Please enter valid password!"); } else { if (Password.length() > 5) { valid = true; textInputLayoutPassword.setError(null); } else { valid = false; textInputLayoutPassword.setError("Password is to short!"); } } return valid; } }
- activity_login.xml
Untuk membuat layout halaman login, silahkan ketikan kode-kode dibawah ini.
<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:tools="http://schemas.android.com/tools" android:background="@color/colorPrimary" android:fitsSystemWindows="true" tools:context=".LoginActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_marginLeft="16dp" android:layout_marginRight="16dp" android:orientation="vertical"> <ImageView android:id="@+id/imageView" android:layout_width="100dp" android:layout_height="100dp" android:layout_gravity="center_horizontal" android:layout_margin="16dp" android:src="@drawable/usericon" /> <android.support.design.widget.TextInputLayout android:id="@+id/textInputLayoutEmail" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" app:errorEnabled="true"> <android.support.design.widget.TextInputEditText android:id="@+id/editTextEmail" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/email" android:inputType="textEmailAddress" /> </android.support.design.widget.TextInputLayout> <android.support.design.widget.TextInputLayout android:id="@+id/textInputLayoutPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp" app:errorEnabled="true" app:passwordToggleEnabled="true" app:passwordToggleTint="@color/colorAccent"> <android.support.design.widget.TextInputEditText android:id="@+id/editTextPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/password" android:inputType="textPassword" /> </android.support.design.widget.TextInputLayout> <Button android:id="@+id/buttonLogin" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="16dp" android:background="@color/colorAccent" android:text="@string/login" android:textColor="@android:color/white" /> <TextView android:id="@+id/textViewCreateAccount" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="16dp" android:layout_marginTop="16dp" android:gravity="center_horizontal" /> </LinearLayout> </ScrollView>
8. Activity Register
Buat activity register dengan cara klik java > klik kanan nama package > New > Activity > Empty Activity > Isikan Nama RegisterActivity. Sehingga akan terdapat class java RegisterActivity.java dan layout activity_register.xml.
- RegisterActivity.java
Untuk kode-kode RegisterActivity.java (tempatkan dibawah nama package) adalah :
import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.support.design.widget.TextInputLayout; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class RegisterActivity extends AppCompatActivity { //Declaration EditTexts EditText editTextUserName; EditText editTextEmail; EditText editTextPassword; //Declaration TextInputLayout TextInputLayout textInputLayoutUserName; TextInputLayout textInputLayoutEmail; TextInputLayout textInputLayoutPassword; //Declaration Button Button buttonRegister; //Declaration SqliteHelper SqliteHelper sqliteHelper; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); sqliteHelper = new SqliteHelper(this); initTextViewLogin(); initViews(); buttonRegister.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (validate()) { String UserName = editTextUserName.getText().toString(); String Email = editTextEmail.getText().toString(); String Password = editTextPassword.getText().toString(); //Check in the database is there any user associated with this email if (!sqliteHelper.isEmailExists(Email)) { //Email does not exist now add new user to database sqliteHelper.addUser(new User(null, UserName, Email, Password)); Snackbar.make(buttonRegister, "User created successfully! Please Login ", Snackbar.LENGTH_LONG).show(); new Handler().postDelayed(new Runnable() { @Override public void run() { finish(); } }, Snackbar.LENGTH_LONG); }else { //Email exists with email input provided so show error user already exist Snackbar.make(buttonRegister, "User already exists with same email ", Snackbar.LENGTH_LONG).show(); } } } }); } //this method used to set Login TextView click event private void initTextViewLogin() { TextView textViewLogin = (TextView) findViewById(R.id.textViewLogin); textViewLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); } //this method is used to connect XML views to its Objects private void initViews() { editTextEmail = (EditText) findViewById(R.id.editTextEmail); editTextPassword = (EditText) findViewById(R.id.editTextPassword); editTextUserName = (EditText) findViewById(R.id.editTextUserName); textInputLayoutEmail = (TextInputLayout) findViewById(R.id.textInputLayoutEmail); textInputLayoutPassword = (TextInputLayout) findViewById(R.id.textInputLayoutPassword); textInputLayoutUserName = (TextInputLayout) findViewById(R.id.textInputLayoutUserName); buttonRegister = (Button) findViewById(R.id.buttonRegister); } //This method is used to validate input given by user public boolean validate() { boolean valid = false; //Get values from EditText fields String UserName = editTextUserName.getText().toString(); String Email = editTextEmail.getText().toString(); String Password = editTextPassword.getText().toString(); //Handling validation for UserName field if (UserName.isEmpty()) { valid = false; textInputLayoutUserName.setError("Please enter valid username!"); } else { if (UserName.length() > 5) { valid = true; textInputLayoutUserName.setError(null); } else { valid = false; textInputLayoutUserName.setError("Username is to short!"); } } //Handling validation for Email field if (!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches()) { valid = false; textInputLayoutEmail.setError("Please enter valid email!"); } else { valid = true; textInputLayoutEmail.setError(null); } //Handling validation for Password field if (Password.isEmpty()) { valid = false; textInputLayoutPassword.setError("Please enter valid password!"); } else { if (Password.length() > 5) { valid = true; textInputLayoutPassword.setError(null); } else { valid = false; textInputLayoutPassword.setError("Password is to short!"); } } return valid; } }
- activity_register.xml
Masukan koe-kode dibawah ini untuk merancang layout register.
<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:tools="http://schemas.android.com/tools" android:background="@color/colorPrimary" android:fitsSystemWindows="true" tools:context=".RegisterActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_marginLeft="16dp" android:layout_marginRight="16dp" android:orientation="vertical"> <ImageView android:id="@+id/imageView" android:layout_width="100dp" android:layout_height="100dp" android:layout_gravity="center_horizontal" android:layout_margin="10dp" android:src="@drawable/usericon" /> <android.support.design.widget.TextInputLayout app:errorEnabled="true" android:id="@+id/textInputLayoutUserName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp"> <android.support.design.widget.TextInputEditText android:id="@+id/editTextUserName" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/username" android:inputType="textPersonName" /> </android.support.design.widget.TextInputLayout> <android.support.design.widget.TextInputLayout android:id="@+id/textInputLayoutEmail" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" app:errorEnabled="true"> <android.support.design.widget.TextInputEditText android:id="@+id/editTextEmail" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/email" android:inputType="textEmailAddress" /> </android.support.design.widget.TextInputLayout> <android.support.design.widget.TextInputLayout android:id="@+id/textInputLayoutPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp" app:errorEnabled="true" app:passwordToggleEnabled="true" app:passwordToggleTint="@color/colorAccent"> <android.support.design.widget.TextInputEditText android:id="@+id/editTextPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/password" android:inputType="textPassword" /> </android.support.design.widget.TextInputLayout> <Button android:id="@+id/buttonRegister" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="@android:color/white" android:layout_gravity="center_horizontal" android:layout_marginTop="10dp" android:layout_weight="1" android:background="@color/colorAccent" android:text="@string/register" /> <TextView android:id="@+id/textViewLogin" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="10dp" android:gravity="center" android:text="@string/back_to_login" android:textColor="@android:color/white" /> </LinearLayout> </ScrollView>
9. Class SqliteHelper
Tambahkan class SqliteHelper. Untuk membuatnya silahkan klik folder java > klik kanan pada nama package > pilih new > class > beri nama class SqliteHelper. Masukan kode-kode berikut ini pada SqliteHelper.java (tempatkan dibawah nama package).
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class SqliteHelper extends SQLiteOpenHelper { //DATABASE NAME public static final String DATABASE_NAME = "loopwiki.com"; //DATABASE VERSION public static final int DATABASE_VERSION = 1; //TABLE NAME public static final String TABLE_USERS = "users"; //TABLE USERS COLUMNS //ID COLUMN @primaryKey public static final String KEY_ID = "id"; //COLUMN user name public static final String KEY_USER_NAME = "username"; //COLUMN email public static final String KEY_EMAIL = "email"; //COLUMN password public static final String KEY_PASSWORD = "password"; //SQL for creating users table public static final String SQL_TABLE_USERS = " CREATE TABLE " + TABLE_USERS + " ( " + KEY_ID + " INTEGER PRIMARY KEY, " + KEY_USER_NAME + " TEXT, " + KEY_EMAIL + " TEXT, " + KEY_PASSWORD + " TEXT" + " ) "; public SqliteHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { //Create Table when oncreate gets called sqLiteDatabase.execSQL(SQL_TABLE_USERS); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { //drop table to create new one if database version updated sqLiteDatabase.execSQL(" DROP TABLE IF EXISTS " + TABLE_USERS); } //using this method we can add users to user table public void addUser(User user) { //get writable database SQLiteDatabase db = this.getWritableDatabase(); //create content values to insert ContentValues values = new ContentValues(); //Put username in @values values.put(KEY_USER_NAME, user.userName); //Put email in @values values.put(KEY_EMAIL, user.email); //Put password in @values values.put(KEY_PASSWORD, user.password); // insert row long todo_id = db.insert(TABLE_USERS, null, values); } public User Authenticate(User user) { SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.query(TABLE_USERS,// Selecting Table new String[]{KEY_ID, KEY_USER_NAME, KEY_EMAIL, KEY_PASSWORD},//Selecting columns want to query KEY_EMAIL + "=?", new String[]{user.email},//Where clause null, null, null); if (cursor != null && cursor.moveToFirst()&& cursor.getCount()>0) { //if cursor has value then in user database there is user associated with this given email User user1 = new User(cursor.getString(0), cursor.getString(1), cursor.getString(2), cursor.getString(3)); //Match both passwords check they are same or not if (user.password.equalsIgnoreCase(user1.password)) { return user1; } } //if user password does not matches or there is no record with that email then return @false return null; } public boolean isEmailExists(String email) { SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.query(TABLE_USERS,// Selecting Table new String[]{KEY_ID, KEY_USER_NAME, KEY_EMAIL, KEY_PASSWORD},//Selecting columns want to query KEY_EMAIL + "=?", new String[]{email},//Where clause null, null, null); if (cursor != null && cursor.moveToFirst()&& cursor.getCount()>0) { //if cursor has value then in user database there is user associated with this given email so return true return true; } //if email does not exist return false return false; } }
Di dalam Class SqliteHelper merupakan bagian dari SQLiteOpenHelper di dalamnya terdapat :
- Nama database
- Versi database
- Tabel
- Kolom
10. Class User
Tambahkan class User yang akan dijadikan model dari user. Untuk membuatnya sama seperti point 8, lalu beri nama class User. Tambahkan kode-kode dibawah ini pada User.java.
public class User { public String id; public String userName; public String email; public String password; public User(String id, String userName, String email, String password) { this.id = id; this.userName = userName; this.email = email; this.password = password; } }
11. Home Screen
Jika login berhasil maka aplikasi akan menampilkan home screen. Home screen yang kita buat kali ini hanya menampilkan komponen TextView.Tambahkan kode-kode dibawah ini pada 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="badoystudio.com.loginsqlite.MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20sp" android:text="Kamu telah berhasil login " app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout>
12. Android Manifest
Buka AndroidManifest.xml yang ada pada folder app > manifest. Edit kode-kodenya sehingga menjadi seperti dibawah ini(pakcagenya sesuaikan dengan nama package yang kamu buat).
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="badoystudio.com.loginsqlite"> <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" android:theme="@style/AppTheme.NoActionBar"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".RegisterActivity" android:label="@string/app_name" android:theme="@style/AppTheme.NoActionBar" /> <activity android:name=".MainActivity" android:label="Home Screen" android:theme="@style/AppTheme.NoActionBar" /> </application> </manifest>
13. Running Project
Running project menggunakan emulator bawaan anroid, genymotion, atau langsung melalui smartphone android yang kamu miliki. Maka hasil akhirnya adalah seperti gambar dibawah ini.
Ternyata mudah ya untuk membuat login di android menggunakan database sqlite. Jangan lupa share.