sobatcoding.com - Tutorial membuat form login menggunakan Java Android Studio dan REST API
Artikel kali ini kita akan membahasa cara membuat form login menggunakan Android Studio Java dan REST API. Kita juga akan menyimpan session login tersebut di aplikasi. Bagaimana caranya? Kita ikuti step bay step nya
Kalian bisa buat project baru terlebih dahulu ata menggunakan project yang sudah ada
Untuk pemanggilan REST API kita akan menggunakan library volley
implementation 'com.android.volley:volley:1.2.1'
Tambahkan permission untuk access ke INTERNET
<uses-permission android:name="android.permission.INTERNET" />
jangan lupa tambahkan juga android:supportsRtl="true"
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
Buatlah layout baru bernama activity_login.xml dan activity java class bernama LoginActivity.java
Pada layout activity_login.xml buatlah seperti berikut
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@color/light"
android:orientation="vertical"
tools:context=".LoginActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TextView
android:id="@+id/txtInfo1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15sp"
android:gravity="center"
android:paddingLeft="25sp"
android:paddingRight="25sp"
android:textSize="24sp"
android:textColor="@color/black"
android:text="Login"
android:textStyle="bold"/>
<TextView
android:id="@+id/txtInfo2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="15dp"
android:gravity="center"
android:paddingLeft="25sp"
android:paddingRight="25sp"
android:textSize="14sp"
android:textColor="@color/black"
android:text="Silahkan login untuk melanjutkan" />
<androidx.cardview.widget.CardView
android:id="@+id/cardLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16sp"
android:layout_marginRight="16sp"
android:layout_marginBottom="16sp"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TextView
android:id="@+id/txtLabelEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="25sp"
android:paddingRight="25sp"
android:layout_marginTop="16sp"
android:layout_marginBottom="5dp"
android:textSize="12sp"
android:text="E-mail"
android:textStyle="bold"/>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="E-mail Anda"
android:paddingLeft="25sp"
android:paddingRight="25sp"
android:layout_marginBottom="10sp">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/inputEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:importantForAutofill="noExcludeDescendants"
android:inputType="textFilter|textMultiLine"
android:textColorHint="@drawable/selector"
app:boxBackgroundColor="@android:color/transparent"
android:background="@android:color/transparent"
android:textColorLink="@color/muted"
android:textSize="14sp" />
</com.google.android.material.textfield.TextInputLayout>
<TextView
android:id="@+id/txtLabelPwd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="25sp"
android:paddingRight="25sp"
android:layout_marginBottom="5dp"
android:textSize="12sp"
android:text="Password"
android:textStyle="bold"/>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password Anda"
android:paddingLeft="25sp"
android:paddingRight="25sp"
android:layout_marginBottom="16sp">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/inputPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColorHint="@drawable/selector"
app:boxBackgroundColor="@android:color/transparent"
android:background="@android:color/transparent"
android:inputType="textPassword|textMultiLine"
android:textColorLink="@color/muted"
android:textSize="14sp" />
</com.google.android.material.textfield.TextInputLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/btnLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="25sp"
android:layout_marginLeft="16sp"
android:layout_marginRight="16sp"
android:padding="15sp"
android:text="@string/txt_login"
android:textColor="@color/white"
android:textSize="14sp"
android:background="@color/success"/>
</LinearLayout>
</ScrollView>
</LinearLayout>
Buatlah java class baru bernama BASEURL. Di dalam BASEURL kita akan menyimpan global variable dari REST API yang kita gunakan
public class BASEURL {
private static final String ROOT_URL = "http://55.55.55.11/absensi/";
private static final String ROOT_API = ROOT_URL + "api/";
public static final String URL_ASSET = ROOT_URL;
public static final String URL_LOGIN= ROOT_API + "login";
public static final String ACCESS_TOKEN = "25d55ad283aa400af464c76d713c07ad";
}
Sebagai contoh kita punya domain http://55.55.55.11/presensi/
Buatlah java class baru bernama VolleySingleton kemudian tambahkan kode berikut:
import android.content.Context;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
public class VolleySingleton {
private static VolleySingleton mInstance;
private RequestQueue mRequestQueue;
private static Context mCtx;
private VolleySingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
}
public static synchronized VolleySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new VolleySingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
}
Buatlah class java bernama User.java
public class User {
private String id, email, nama;
public User(String id, String email, String nama) {
this.id = id;
this.email= email;
this.nama = nama;
}
public String getId() {
return id;
}
public String getEmail() {
return email;
}
}
Buatlah classs java bernama Shared.java. Shared.java ini nantinya akan kita gunakan untuk menyimpan session dan menghapus session
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
public class Shared {
//the constants
private static final String SHARED_PREF_NAME = "session_login";
private static final String KEY_ID = "key_id";
private static final String KEY_EMAIL = "key_email";
private static final String KEY_NAME = "key_name";
private static Shared mInstance;
private static Context mCtx;
private Shared(Context context) {
mCtx = context;
}
public static synchronized Shared getInstance(Context context) {
if (mInstance == null) {
mInstance = new Shared(context);
}
return mInstance;
}
public boolean isLoggedIn() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(KEY_ID, null) != null;
}
public void userLogin(User user) {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(KEY_ID, user.getId());
editor.putString(KEY_EMAIL, user.getEmail());
editor.putString(KEY_NAME, user.getNama());
editor.apply();
}
public User getUser() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return new User(
sharedPreferences.getString(KEY_ID, null),
sharedPreferences.getString(KEY_EMAIL, null),
sharedPreferences.getString(KEY_NAME, null)
);
}
public void logout() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
mCtx.startActivity(new Intent(mCtx, LoginActivity.class));
}
}
Source code :
public class LoginActivity extends AppCompatActivity {
ProgressDialog pDialog;
EditText editTextEmail, editTextPassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
editTextEmail = findViewById(R.id.inputEmail);
editTextPassword = findViewById(R.id.inputPassword);
findViewById(R.id.btnLogin).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final String email = editTextEmail.getText().toString();
final String pwd = editTextPassword.getText().toString();
if( email.isEmpty() )
{
editTextEmail.setError("Mohon masukkan email dengan benar");
editTextEmail.requestFocus();
return;
}
if( pwd.isEmpty() )
{
editTextPassword.setError("Mohon masukkan password dengan benar");
editTextPassword.requestFocus();
return;
}
userLogin(email, pwd);
}
});
}
....
Kita buat void function bernama userLogin
private void userLogin( final String email, final String password) {
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
pDialog.setMessage("Sedang memproses ...");
showDialog();
StringRequest stringRequest = new StringRequest(Request.Method.POST, BASEURL.URL_LOGIN,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
hideDialog();
try {
//converting response to json object
JSONObject obj = new JSONObject(response);
//if no error in response
if ( obj.getBoolean("success")) {
//getting the user from the response
JSONObject loginJson = obj.getJSONObject("data");
User user = new User (
loginJson.getString("id"),
loginJson.getString("email"),
loginJson.getString("nama")
);
//create session
Shared.getInstance(getApplicationContext()).userLogin(user);
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}else{
hideDialog();
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
//Log.i("TAG","Error :" + e.printStackTrace().toString());
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
hideDialog();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
Log.i("TAG","Error :" + error.getMessage());
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Authorization", BASEURL.ACCESS_TOKEN);
return params;
}
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", password);
return params;
}
};
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
Contoh di atas kita login menggunakan REST API dan menambahkan Authorization pada header menggunakan Volley Library
Jika login berhasil otomatis create session dan akan di direct ke MainActivity
//create session
Shared.getInstance(getApplicationContext()).userLogin(user);
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
Untuk REST API, kita gunakan Codeigniter 3 dengan contoh source code seperti berikut :
public function login()
{
//validation
$error = [];
if( !$this->getPost('email')) $error[] = 'Email harus diisi';
if (!filter_var($this->getPost('email'), FILTER_VALIDATE_EMAIL)) $error[] = 'Format email salah';
if( !$this->getPost('password')) $error[] = 'Password harus diisi';
if( count($error) > 0 )
{
$this->response(['success' => false, 'message' => $error[0] ], 422);
}
$login = $this->User->ceckLogin($this->getPost('email'), $this->getPost('password'));
if( $login )
{
$this->response(['success' => true, 'data' => $login->pegawai]);
}else{
$this->response(['success' => false, 'message' => 'Gagal login! Invalid email/password']);
}
}
source code User.php
<?php
class User extends CI_Model {
public function ceckLogin($email, $pass)
{
$row = $this->db->select('id, email, password')->get_where("users", ['email' => $email, 'status' => 1])->row();
if($row)
{
if( password_verify($pass, $row->password ) )
{
$this->db->where("id", $row->id);
$this->db->update('users', ['last_login' => date("Y-m-d H:i:s")]);
$row->pegawai = $this->db->select('id, email, nama')->get_where('id', ['id' => $row->id])->row();
unset($row->password);
return $row;
}
}
return null;
}
Untuk kalian yang belum tahu cara membuat REST API menggunakan Codeigniter 3, kalian bisa membaca artikel berikut : REST API Sederhana Menggunakan Codeigniter 3
Sekian tutorial kali ini. Jika teman-teman memiliki pertanyaan atau saran mengenai artikel ini, jangan ragu untuk meninggalkan komentar pada form di bawah ini.
Semoga bermanfaat.
Komentar 0