Android Studio Tutorial Php Mysql Login And Register

Login dan Registrasi sangat belalah kita temukan di beberapa permintaan yang berbasis client peladen. Lega postingan kelihatannya ini saya akan memasrahkan tutorial membentuk login dan registrasi di Android dengan
PHP
&
MySQL.

Bagi mengkoneksikan antara permintaan android dengan server, kita perlu membuat
Jago merah
(Application Programming Interface) bagaikan jembatan penghubungnya.

Setelah itu mendesain database sekaligus menginteraksikannya dengan
API.

Sebelum kita memulai, pastikan laptop/notebook mutakadim terinstall
XAMPP.

1. Install XAMPP

Download dan install XAMPP di sini https://www.apachefriends.org/index.html

2. Untuk Database MySQL

Buka http://localhost/phpmyadmin kemudian bagi database hijau dengan segel
simple_db. Setelah itu buat table dengan merek
users
nan berisi field-field berikut.

3. Buat Api

Langkah selanjutnya adalah mewujudkan API. Dalam kejadian ini kita membuat Api menggunakan PHP 5.

Buka folder
xampp

htdocs
dan buat folder dengan jenama
simple_api.

Di dalam folder simple_api, buat php file dengan tanda
connect.php.

Connect.php

<?php      define('_HOST_NAME','localhost');      define('_DATABASE_NAME','simple_db');      define('_DATABASE_USER_NAME','root');      define('_DATABASE_PASSWORD','');        $MySQLiconn = new MySQLi(_HOST_NAME,_DATABASE_USER_NAME,_DATABASE_PASSWORD,_DATABASE_NAME);         if($MySQLiconn->connect_errno) {        die("ERROR : -> ".$MySQLiconn->connect_error);      }   ?>
      

Kemudian buat file
register.php
dan include-kan
connect.php
berikut.

<?php  include_once 'connect.php';  $response = array("error" => FALSE);  if (isset($_POST['firstname']) && isset($_POST['lastname']) && isset($_POST['email']) && isset($_POST['password'])) {  $firstname = htmlspecialchars($_POST['firstname']);  $lastname = htmlspecialchars($_POST['lastname']);  $email = htmlspecialchar($_POST['email']);  $password = htmlspecialchars($_POST['password']);    $encrypted_password = hash("sha256", $password);// encrypted password          $sql = $MySQLiconn->query("SELECT email from users WHERE email = '$email'");      if(mysqli_num_rows($sql) > 0) {   $response["error"] = TRUE;         $response["message"] = "User already existed";          echo json_encode($response);     }else{      $sql = $MySQLiconn->query("INSERT INTO users(firstname, lastname, email, password, created_at) VALUES('$firstname', '$lastname', '$email', '$encrypted_password', NOW())");        if($sql) {          $response["error"] = FALSE;          $response["message"] = "Register Successfull";     echo json_encode($response);      } else {       $response["error"] = TRUE;          $response["message"] = "Register Failure";     echo json_encode($response);      }         }      } ?>
      

Kemudian kerjakan file
login.php
berikut :

<?php  include_once 'connect.php';  $response = array("error" => FALSE);  if (isset($_POST['email']) && isset($_POST['password'])) {    $email = htmlspecialchars($_POST['email']);  $password = htmlspecialchars($_POST['password']);   $encrypted_password = hash("sha256", $password);// encrypted password           $sql = $MySQLiconn->query("SELECT * FROM users WHERE email='$email' AND password='$encrypted_password'");   if(mysqli_num_rows($sql) > 0){   while($row = $sql->fetch_array()){    $response["error"] = FALSE;        $response["message"] = "Login Successfull";        $response["data"]["firstname"] = $row['firstname'];        $response["data"]["lastname"] = $row['lastname'];        $response["data"]["email"] = $row['email'];       }    echo json_encode($response);    }else{     $response["error"] = TRUE;      $response["message"] = "Incorrect Email or Password!";    echo json_encode($response);    } }  ?>
      

4. Untuk Android Project

Setelah kita membuat Jago merah, berikutnya yakni mewujudkan project baru di Android. Tuntutan nan dibuat nantinya memiliki 3 tampilan yakni
Login,
Registration
dan
Dashboard.

Pertama, tambahkan library yang diperlukan di gradle.

Bagi library networking kita menggunakan Retrofit 2. Penjelasan dan implementasi Retrofit 2 dalam dilihat di postingan saya sebelumnya http://wimsonevel.blogspot.co.id/2016/07/tutorial-android-http-client-on-android.html

dependencies {     compile fileTree(dir: 'libs', include: ['*.jar'])     testCompile 'junit:junit:4.12'     compile 'com.android.support:appcompat-v7:24.2.1'      compile 'com.squareup.retrofit2:retrofit:2.1.0'     compile 'com.squareup.retrofit2:converter-gson:2.1.0'     compile "com.squareup.okhttp3:logging-interceptor:3.3.0" }
      

Buat struktur projectnya perumpamaan berikut :

Edit dan tambahkan sejumlah resources string di
strings.xml
berikut :

<resources>     <string name="app_name">AndroidLoginAndRegistration</string>     <string name="email">Email</string>     <string name="password">Password</string>     <string name="login">Login</string>     <string name="register">Register</string>     <string name="register_caption">Dont have an account? Register</string>     <string name="title_activity_register">RegisterActivity</string>     <string name="first_name">First Name</string>     <string name="last_name">Last Name</string>     <string name="logout">Logout</string>     <string name="greeting">Hi, %s :)</string> </resources>
      

Edit dan tambahkan beberapa resources color di color.xml berikut :

<?xml version="1.0" encoding="utf-8"?> <resources>     <color name="colorPrimary">#2196F3</color>     <color name="colorPrimaryDark">#1565C0</color>     <color name="colorAccent">#1976D2</color>     <color name="colorWhite">#FFFFFF</color>     <color name="colorGray">#E5E5E5</color>     <color name="colorText">#8A8A8A</color> </resources>

Edit dan tambahkan beberapa resource drawable berikut :

btn_normal.xml

<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"     android:shape="rectangle" >     <solid android:color="@color/colorWhite"/>     <corners android:lingkup="4dp" />     <padding         android:bottom="5dp"         android:left="5dp"         android:right="5dp"         android:top="5dp" /> </shape>
      

btn_normal_2.xml

<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"     android:shape="rectangle" >     <solid android:color="@color/colorPrimary"/>     <corners android:radius="4dp" />     <padding         android:bottom="5dp"         android:left="5dp"         android:right="5dp"         android:top="5dp" /> </shape>
      

btn_pressed.xml

<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"     android:shape="rectangle" >     <solid android:color="@color/colorGray"/>     <corners android:jangkauan="4dp" />     <padding         android:bottom="5dp"         android:left="5dp"         android:right="5dp"         android:top="5dp" /> </shape>
      

btn_pressed_2.xml

<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"     android:shape="rectangle" >     <solid android:color="@color/colorPrimaryDark"/>     <corners android:jangkauan="4dp" />     <padding         android:bottom="5dp"         android:left="5dp"         android:right="5dp"         android:top="5dp" /> </shape>
      

btn_background.xml

<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android">     <item android:state_pressed="true"         android:drawable="@drawable/btn_pressed" /> <!-- pressed -->     <item android:state_focused="true"         android:drawable="@drawable/btn_normal" /> <!-- focused -->     <item android:drawable="@drawable/btn_normal" /> <!-- default --> </selector>
      

btn_background_2.xml

<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android">     <item android:state_pressed="true"         android:drawable="@drawable/btn_pressed_2" /> <!-- pressed -->     <item android:state_focused="true"         android:drawable="@drawable/btn_normal_2" /> <!-- focused -->     <item android:drawable="@drawable/btn_normal_2" /> <!-- default --> </selector>
      

Lebih jauh kerjakan bilang layout untuk Login, Registrasi dan Dashboard berikut :

activity_login.xml

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"     android:paddingLeft="@dimen/activity_horizontal_margin"     android:paddingRight="@dimen/activity_horizontal_margin"     android:paddingTop="@dimen/activity_vertical_margin"     android:windowSoftInputMode="adjustResize"     android:background="@color/colorPrimary"     tools:context="com.wimso.androidloginandregistration.MainActivity">      <LinearLayout         android:orientation="vertical"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_centerVertical="true"         android:layout_centerHorizontal="true">          <EditText             android:id="@+id/email"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:inputType="textEmailAddress"             android:ems="10"             android:hint="@string/email"             android:textColor="@color/colorWhite"             android:textColorHint="@color/colorWhite"             android:padding="@dimen/activity_vertical_margin"             android:theme="@style/WhiteFocus"/>          <EditText             android:id="@+id/password"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:inputType="textPassword"             android:ems="10"             android:hint="@string/password"             android:textColor="@color/colorWhite"             android:textColorHint="@color/colorWhite"             android:padding="@dimen/activity_vertical_margin"             android:layout_marginTop="@dimen/activity_vertical_margin"             android:theme="@style/WhiteFocus" />      </LinearLayout>      <LinearLayout         android:orientation="vertical"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_alignParentBottom="true"         android:layout_centerHorizontal="true">          <Button             android:id="@+id/btn_login"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:text="@string/login"             android:background="@drawable/btn_background"             android:textColor="@color/colorPrimary"/>          <TextView             android:id="@+id/register_caption"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:textAppearance="?android:attr/textAppearanceMedium"             android:text="@string/register_caption"             android:layout_marginTop="@dimen/activity_vertical_margin"             android:gravity="center"             android:textColor="@color/colorWhite" />      </LinearLayout>  </RelativeLayout>
      

activity_register.xml

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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:windowSoftInputMode="adjustResize"     android:background="@color/colorPrimary"     tools:context="com.wimso.androidloginandregistration.RegisterActivity">      <android.support.v7.widget.Toolbar         xmlns:android="http://schemas.android.com/apk/res/android"         xmlns:app="http://schemas.android.com/apk/res-auto"         android:id="@+id/toolbar"         android:layout_width="match_parent"         android:layout_height="?actionBarSize"         android:background="?colorPrimary"         app:popupTheme="@style/ThemeOverlay.AppCompat.Light"         android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />      <LinearLayout         android:layout_width="match_parent"         android:layout_height="wrap_content"         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"         android:layout_centerVertical="true"         android:layout_centerHorizontal="true">          <EditText             android:id="@+id/firstname"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:inputType="textPersonName"             android:hint="@string/first_name"             android:textColor="@color/colorWhite"             android:textColorHint="@color/colorWhite"             android:ems="10"             android:padding="@dimen/activity_vertical_margin"             android:theme="@style/WhiteFocus" />          <EditText             android:id="@+id/lastname"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:inputType="textPersonName"             android:hint="@string/last_name"             android:textColor="@color/colorWhite"             android:textColorHint="@color/colorWhite"             android:ems="10"             android:padding="@dimen/activity_vertical_margin"             android:theme="@style/WhiteFocus" />          <EditText             android:id="@+id/email"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:inputType="textEmailAddress"             android:hint="@string/email"             android:textColor="@color/colorWhite"             android:textColorHint="@color/colorWhite"             android:ems="10"             android:padding="@dimen/activity_vertical_margin"             android:theme="@style/WhiteFocus" />          <EditText             android:id="@+id/password"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:inputType="textPassword"             android:hint="@string/password"             android:textColor="@color/colorWhite"             android:textColorHint="@color/colorWhite"             android:ems="10"             android:padding="@dimen/activity_vertical_margin"             android:theme="@style/WhiteFocus" />      </LinearLayout>      <LinearLayout         android:orientation="vertical"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:paddingBottom="@dimen/activity_vertical_margin"         android:paddingLeft="@dimen/activity_horizontal_margin"         android:paddingRight="@dimen/activity_horizontal_margin"         android:paddingTop="@dimen/activity_vertical_margin"         android:layout_alignParentBottom="true"         android:layout_centerHorizontal="true">          <Button             android:id="@+id/btn_register"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:text="@string/register"             android:background="@drawable/btn_background"             android:textColor="@color/colorPrimary" />      </LinearLayout>  </RelativeLayout>
      

activity_main.xml

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"     android:paddingLeft="@dimen/activity_horizontal_margin"     android:paddingRight="@dimen/activity_horizontal_margin"     android:paddingTop="@dimen/activity_vertical_margin"     android:windowSoftInputMode="adjustResize"     tools:context="com.wimso.androidloginandregistration.MainActivity">      <LinearLayout         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_centerVertical="true"         android:layout_centerHorizontal="true"         android:orientation="vertical">          <TextView             android:id="@+id/greeting"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:textAppearance="?android:attr/textAppearanceLarge"             android:textSize="48sp"             android:textColor="@color/colorText" />           <TextView             android:id="@+id/email"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:textAppearance="?android:attr/textAppearanceLarge"             android:textColor="@color/colorText" />      </LinearLayout>      <LinearLayout         android:orientation="vertical"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_alignParentBottom="true"         android:layout_centerHorizontal="true">          <Button             android:id="@+id/btn_logout"             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:text="@string/logout"             android:background="@drawable/btn_background_2"             android:textColor="@color/colorWhite"/>      </LinearLayout>  </RelativeLayout>
      

Bakal package network→ config lalu bikin inferior dengan nama
Config.java. Di papan bawah ini kita akan mendeklarasikan url dan endpoint lega Api yang sudah kita buat. Base url yang ditentukan dari IP localhost yang digunakan.

/**  * Created by Wim on 11/4/16.  */ public class Config {      public static final String BASE_URL = "YOUR IP ADDRESS"; // Your Local IP Address or Localhost (http://10.0.2.2/)      public static final String API_URL = BASE_URL + "/simple_api";      public static final String API_LOGIN = API_URL + "/login.php";     public static final String API_REGISTER = API_URL + "/register.php";  }
      

Masih di package nan sama, buat papan bawah dengan nama
RetrofitBuilder.java

import com.wimso.androidloginandregistration.BuildConfig;  import java.util.concurrent.TimeUnit; import android.content.Context;  import okhttp3.Cache; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory;  /**  * Created by Wim on 11/4/16.  */ public class RetrofitBuilder {      public static Retrofit builder(Context context) {         OkHttpClient.Builder okhttpBuilder = new OkHttpClient().newBuilder();         okhttpBuilder.connectTimeout(60, TimeUnit.SECONDS);         okhttpBuilder.writeTimeout(60, TimeUnit.SECONDS);         okhttpBuilder.readTimeout(60, TimeUnit.SECONDS);          int cacheSize = 10 * 1024 * 1024;         Cache cache = new Cache(context.getCacheDir(), cacheSize);         okhttpBuilder.cache(cache);          if (BuildConfig.DEBUG) {             HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();             interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);             okhttpBuilder.addInterceptor(interceptor);         }          Retrofit retrofit = new Retrofit.Builder()                 .baseUrl(Config.BASE_URL)                 .client(okhttpBuilder.build())                 .addConverterFactory(GsonConverterFactory.create())                 .build();          return retrofit;     } }
      

Dari package network, buat package interfaces kemudian tambahkan interface
LoginInterface.java
dan
RegisterInterface.java.

LoginInterface.java

import com.wimso.androidloginandregistration.model.User; import com.wimso.androidloginandregistration.network.config.Config;  import retrofit2.Call; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.POST;  /**  * Created by Wim on 11/3/16.  */ public interface LoginInterface {      @FormUrlEncoded     @POST(Config.API_LOGIN)     Call<User> login(             @Field("email") String email,             @Field("password") String password);  }
      

RegisterInterface.java

import com.wimso.androidloginandregistration.teladan.BaseResponse; import com.wimso.androidloginandregistration.network.config.Config;  import retrofit2.Call; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.POST;  /**  * Created by Wim on 11/4/16.  */ public interface RegisterInterface {      @FormUrlEncoded     @POST(Config.API_REGISTER)     Call<BaseResponse> register(             @Field("firstname") String firstname,             @Field("lastname") String lastname,             @Field("email") String email,             @Field("password") String password);  }
      

Kemudian di package network buat inferior
LoginService.java
dan
RegisterService.java
berikut :

LoginService.java

import android.content.Context;  import com.wimso.androidloginandregistration.network.config.RetrofitBuilder; import com.wimso.androidloginandregistration.network.interfaces.LoginInterface;  import retrofit2.Callback;  /**  * Created by Wim on 11/4/16.  */ public class LoginService {      private LoginInterface loginInterface;      public LoginService(Context context) {         loginInterface = RetrofitBuilder.builder(context)                 .create(LoginInterface.class);     }      public void doLogin(String email, String password, Callback callback) {         loginInterface.login(email, password).enqueue(callback);     }  }
      

RegisterService.java

import android.content.Context;  import com.wimso.androidloginandregistration.network.config.RetrofitBuilder; import com.wimso.androidloginandregistration.network.interfaces.RegisterInterface;  import retrofit2.Callback;  /**  * Created by Wim on 11/4/16.  */ public class RegisterService {      private RegisterInterface registerInterface;      public RegisterService(Context context) {         registerInterface = RetrofitBuilder.builder(context)                 .create(RegisterInterface.class);     }      public void doRegister(String firstname, String lastname, String email, String password, Callback callback) {         registerInterface.register(firstname, lastname, email, password).enqueue(callback);     }  }
      

Kemudian untuk package
ideal
yang kebal kelas model datanya sesuai dengan response json yang akan di mapping dalam bentuk kelas pojos.

Buat kelas dengan nama
BaseResponse.java

/**  * Created by Wim on 11/4/16.  */ public class BaseResponse {      private boolean error;     private String message;      public BaseResponse() {     }      public boolean isError() {         return error;     }      public void setError(boolean error) {         this.error = error;     }      public String getMessage() {         return message;     }      public void setMessage(String message) {         this.message = message;     } }
      

Buat kelas dengan nama
User.java

/**  * Created by Wim on 11/4/16.  */ public class User extends BaseResponse {      private UserData data;      public User() {     }      public UserData getData() {         return data;     }      public void setData(UserData data) {         this.data = data;     } }
      

Buat kelas dengan keunggulan
UserData.java

/**  * Created by Wim on 11/4/16.  */ public class UserData {      private String firstname;     private String lastname;     private String email;      public UserData() {     }      public String getFirstname() {         return firstname;     }      public void setFirstname(String firstname) {         this.firstname = firstname;     }      public String getLastname() {         return lastname;     }      public void setLastname(String lastname) {         this.lastname = lastname;     }      public String getEmail() {         return email;     }      public void setEmail(String email) {         this.email = email;     } }
      

Lebih lanjut buat package
util
kemudian buat kelas
PrefUtil.java
untuk menyimpan data di SharedPreferences.

import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager;  import com.google.gson.Gson; import com.wimso.androidloginandregistration.model.User;  /**  * Created by Wim on 11/3/16.  */ public class PrefUtil {      public static final String USER_SESSION = "user_session";      public static SharedPreferences getSharedPreference(Context context) {         return PreferenceManager.getDefaultSharedPreferences(context);     }      public static void putUser(Context context, String key, User user) {         Gson gson = new Gson();         String json = gson.toJson(user);         putString(context, key, json);     }      public static User getUser(Context context, String key) {         Gson gson = new Gson();         String json = getString(context, key);         User user = gson.fromJson(json, User.class);         return user;     }      public static void putString(Context context, String key, String value) {         getSharedPreference(context).edit().putString(key, value).apply();     }      public static String getString(Context context, String key) {         return getSharedPreference(context).getString(key, null);     }      public static void clear(Context context) {         getSharedPreference(context).edit().clear().apply();     }  }
      

Buat kelas activity dengan nama
LoginActivity.java
untuk proses login user.

import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.text.Html; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.TextUtils; import android.text.method.LinkMovementMethod; import android.text.style.ClickableSpan; import android.text.style.ForegroundColorSpan; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast;  import com.wimso.androidloginandregistration.teoretis.User; import com.wimso.androidloginandregistration.network.LoginService; import com.wimso.androidloginandregistration.util.PrefUtil;  import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response;  /**  * Created by Wim on 10/31/16.  */ public class LoginActivity extends AppCompatActivity {      private EditText emailText;     private EditText passwordText;     private Button btnLogin;     private TextView registerCaption;      private LoginService loginService;      public static void start(Context context) {         Intent intent = new Intent(context, LoginActivity.class);         context.startActivity(intent);     }      @Override     protected void onCreate(@Nullable Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_login);          if(isSessionLogin()) {             MainActivity.start(this);             LoginActivity.this.finish();         }          emailText = (EditText) findViewById(R.id.email);         passwordText = (EditText) findViewById(R.id.password);         btnLogin = (Button) findViewById(R.id.btn_login);         registerCaption = (TextView) findViewById(R.id.register_caption);          btnLogin.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View view) {                 loginAct();             }         });          String caption = "Dont have an account? <b>Register</b>";         SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(Html.fromHtml(caption));         spannableStringBuilder.setSpan(new ClickableSpan() {             @Override             public void onClick(View view) {                 RegisterActivity.start(LoginActivity.this);             }         }, caption.indexOf("Register") - 3, spannableStringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);         spannableStringBuilder.setSpan(new ForegroundColorSpan(Color.WHITE), caption                 .indexOf("Register") - 3, spannableStringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);          registerCaption.setText(spannableStringBuilder);         registerCaption.setMovementMethod(LinkMovementMethod.getInstance());      }      void loginAct() {         String email = emailText.getText().toString();         String password = passwordText.getText().toString();          if(TextUtils.isEmpty(email)) {             emailText.setError("Email cannot be empty!");             return;         }          if(TextUtils.isEmpty(password)) {             passwordText.setError("Password cannot be empty");             return;         }          loginService = new LoginService(this);         loginService.doLogin(email, password, new Callback() {             @Override             public void onResponse(Call call, Response response) {                 User user = (User) response.body();                  if(user != null) {                     if(!user.isError()) {                         PrefUtil.putUser(LoginActivity.this, PrefUtil.USER_SESSION, user);                         MainActivity.menginjak(LoginActivity.this);                         LoginActivity.this.finish();                     }                      Toast.makeText(LoginActivity.this, user.getMessage(), Toast.LENGTH_SHORT).show();                 }             }              @Override             public void onFailure(Call call, Throwable n) {                 Toast.makeText(LoginActivity.this, "An error occurred!", Toast.LENGTH_SHORT).show();             }         });     }      boolean isSessionLogin() {         return PrefUtil.getUser(this, PrefUtil.USER_SESSION) != null;     } }
      

Buat kelas dengan cap
RegisterActivity.java
bakal proses register user.

import android.content.Context; import android.content.Intent; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast;  import com.wimso.androidloginandregistration.model.BaseResponse; import com.wimso.androidloginandregistration.network.RegisterService;  import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response;  public class RegisterActivity extends AppCompatActivity {      private Toolbar toolbar;      private EditText firstnameText;     private EditText lastnameText;     private EditText emailText;     private EditText passwordText;      private Button btnRegister;      private RegisterService registerService;      public static void start(Context context) {         Intent intent = new Intent(context, RegisterActivity.class);         context.startActivity(intent);     }      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_register);          toolbar = (Toolbar) findViewById(R.id.toolbar);          firstnameText = (EditText) findViewById(R.id.firstname);         lastnameText = (EditText) findViewById(R.id.lastname);         emailText = (EditText) findViewById(R.id.email);         passwordText = (EditText) findViewById(R.id.password);         btnRegister = (Button) findViewById(R.id.btn_register);          setSupportActionBar(toolbar);          ActionBar actionBar = getSupportActionBar();         if(actionBar != null) {             actionBar.setDisplayHomeAsUpEnabled(true);         }          btnRegister.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View view) {                 registerAct();             }         });     }      void registerAct() {         String firstname = firstnameText.getText().toString();         String lastname = lastnameText.getText().toString();         String email = emailText.getText().toString();         String password = passwordText.getText().toString();          if(TextUtils.isEmpty(firstname)) {             firstnameText.setError("Firstname cannot be empty !");             return;         }          if(TextUtils.isEmpty(lastname)) {             firstnameText.setError("Lastname cannot be empty !");             return;         }          if(TextUtils.isEmpty(email)) {             firstnameText.setError("Email cannot be empty !");             return;         }          if(TextUtils.isEmpty(password)) {             firstnameText.setError("Password cannot be empty !");             return;         }          registerService = new RegisterService(this);         registerService.doRegister(firstname, lastname, email, password, new Callback() {             @Override             public void onResponse(Call call, Response response) {                 BaseResponse baseResponse = (BaseResponse) response.body();                  if(baseResponse != null) {                     if(!baseResponse.isError()) {                         LoginActivity.tiba(RegisterActivity.this);                         RegisterActivity.this.finish();                     }                      Toast.makeText(RegisterActivity.this, baseResponse.getMessage(), Toast.LENGTH_SHORT).show();                 }             }              @Override             public void onFailure(Call call, Throwable t) {                 Toast.makeText(RegisterActivity.this, "An error occurred!", Toast.LENGTH_SHORT).show();             }         });      }      @Override     public boolean onOptionsItemSelected(MenuItem item) {         switch (item.getItemId()) {             case android.R.id.home:                 onBackPressed();                 return true;             default:                 return super.onOptionsItemSelected(item);         }     }  }
      

Buat kelas
MainActivity.java
sebagai dashboard user.

import android.content.Context; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView;  import com.wimso.androidloginandregistration.eksemplar.User; import com.wimso.androidloginandregistration.util.PrefUtil;  public class MainActivity extends AppCompatActivity {      private TextView greeting;     private TextView email;     private Button btnLogout;      public static void start(Context context) {         Intent intent = new Intent(context, MainActivity.class);         context.startActivity(intent);     }      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          greeting = (TextView) findViewById(R.id.greeting);         email = (TextView) findViewById(R.id.email);         btnLogout = (Button) findViewById(R.id.btn_logout);          User user = PrefUtil.getUser(this, PrefUtil.USER_SESSION);          greeting.setText(getResources().getString(R.string.greeting, user.getData().getFirstname()));         email.setText(user.getData().getEmail());          btnLogout.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View view) {                 logoutAct();                  LoginActivity.start(MainActivity.this);                 MainActivity.this.finish();             }         });      }      void logoutAct() {         PrefUtil.clear(this);     } }
      

Keladak ialah tambahkan permission internet di AndroidManifest.xml

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

Build dan jalankan maka balasannya sebagai berikut :

Source code sempurna bisa dilihat di https://github.com/wimsonevel/AndroidLoginAndRegistration

Sekian tuntunan pecah saya bisa jadi ini.
Mudahmudahan bermanfaat.

Happy Coding 🙂

Source: http://wimsonevel.blogspot.com/2016/11/tutorial-android-login-and-registration.html