(Tutorial Android) Login and Registration with PHP & MySQL

Thursday, November 10, 2016

Login dan Registrasi sangat sering kita temukan di beberapa aplikasi yang berbasis client server. Pada postingan kali ini saya akan memberikan tutorial membuat login dan registrasi di Android dengan PHP & MySQL.

Untuk mengkoneksikan antara aplikasi android dengan server, kita perlu membuat API (Application Programming Interface) sebagai jembatan penghubungnya.

Setelah itu mendesain database sekaligus menginteraksikannya dengan API.

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

1. Install XAMPP

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

2. Buat Database MySQL

Buka http://localhost/phpmyadmin kemudian buat database baru dengan nama simple_db. Setelah itu buat table dengan nama users yang berisi field-field berikut.


3. Buat API

Langkah selanjutnya adalah membuat API. Dalam hal ini kita membuat API menggunakan PHP 5.

Buka folder xampphtdocs dan buat folder dengan nama simple_api.

Di dalam folder simple_api, buat php file dengan nama 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 buat 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. Buat Android Project

Setelah kita membuat API, berikutnya adalah membuat project baru di Android. Aplikasi yang dibuat nantinya memiliki 3 tampilan yakni Login, Registration dan Dashboard.

Pertama, tambahkan library yang diperlukan di gradle.

Untuk 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 sebagai berikut :


Edit dan tambahkan beberapa 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:radius="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:radius="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:radius="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>
Selanjutnya buat beberapa 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>

Buat package network→ config lalu buat kelas dengan nama Config.java. Di kelas ini kita akan mendeklarasikan url dan endpoint pada API yang telah 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 yang sama, buat kelas 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.model.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 kelas 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 buat package model yang berisi 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 nama 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;
    }
}
Selanjutnya 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.model.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.start(LoginActivity.this);
                        LoginActivity.this.finish();
                    }

                    Toast.makeText(LoginActivity.this, user.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                Toast.makeText(LoginActivity.this, "An error occurred!", Toast.LENGTH_SHORT).show();
            }
        });
    }

    boolean isSessionLogin() {
        return PrefUtil.getUser(this, PrefUtil.USER_SESSION) != null;
    }
}

Buat kelas dengan nama RegisterActivity.java untuk 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.start(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.model.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);
    }
}

Terakhir adalah tambahkan permission internet di AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
Build dan jalankan maka hasilnya sebagai berikut :




Source code lengkap dapat dilihat di https://github.com/wimsonevel/AndroidLoginAndRegistration

Sekian tutorial dari saya kali ini.
Semoga bermanfaat.

Happy Coding :)

Share this :

Previous
Next Post »
105 Komentar
avatar

bagus tutorialnya, sangat membantu.
pak tanya, kalau setelah login berhasil terus menampilkan 'id' usernya gimanaya? kok saya gagal nyoba, mohon bantuannya pak. terimakasih

Balas
avatar

om, kalo apinya saya kaya dibawah, interfacenya gimana yah, saya coba pake kaya di atas ga jadi, makasih.
public function login(){
$data = array();

$username = $this->input->post('f_username');
$password = $this->input->post('f_password');

//check apakah username && password diiisi
if ($username == '' || $password == ''){
$data['result'] = false;
$data['msg'] = "Username atau Password harus diisi";

echo json_encode($data);
return;
}

//check apakah username dan password match dgn data diserver kita
$this->db->where('user_username', $username);
$this->db->where('user_password', md5($password));
$this->db->where('user_status', 1);
$q = $this->db->get('user');

//check hasil quernya
if ($q->num_rows() > 0){
//jika ada buat sesi user dulu
$qq = $q->row();
$token = md5($qq->id_user.date('YmdHis'));

//simpan sesi tokennya
$simpan = array();
$simpan['sesi_key'] = $token;
$simpan['id_user'] = $qq->id_user;
$simpan['sesi_time'] = date('Y-m-d H:i:s');
$hasil = $this->db->insert('sesi', $simpan);
//check hasil simpan sesi
if($hasil){
$data['result'] = true;
$data['token'] = $token;
$data['data'] = $qq;
$data['msg'] = "Selamat datang ".$qq->user_nama;
}else{
$data['result'] = false;
$data['msg'] = "Error create sesi, silahkan coba login lagi";
}
}else{
$data['result'] = false;
$data['msg'] = "Username atau Password tidak sama, silahkan coba lagi";
}

echo json_encode($data);
}

Balas
avatar

pake POST gan di interfacenya..
buat kelas modelnya dulu sesuai response jsonnya, misal :
class Response {

boolean result;
String token;
String data;
String msg;

}

utk interfacenya :

@FormUrlEncoded
@POST("urlnya.... ")
Call <Response> login(
@Field("f_username") String username,
@Field("f_password") String password);

Balas
avatar

ok gan saya coba dulu, tengkiu

Balas
This comment has been removed by the author. - Hapus
This comment has been removed by the author. - Hapus
avatar

hello , saya sudah selsai membuat projectnya ketika saya mau register tidak bisa ? bagaimana ya ? padadahal api registernya sudah benar tetap keluar An error occurred!tolong solusinya gan

Balas
avatar

berarti di apinya ada yg salah gan, coba cek koneksi ke apinya

Balas
avatar

gan punya saya ga bisa login kenapa ya gan , apa pengaruh avd emulatornya?
di logcat tertulis begini
12-31 19:42:08.910 7327-8184/com.logintest D/OkHttp: <-- HTTP FAILED: java.net.ConnectException: Failed to connect to /192.168.168.1:80

Balas
avatar

IPnya salah gan, pake ip komputer agan,, diatas itu cuma saya kasih contoh pake IP saya

Balas
avatar

permisi gan ini salahnya dimana ya adaa notif "An error occurred!". terimakasih sebelumnya gan.

Balas
avatar

di koneksi ke APInya gan, coba di cek IP juga gan

Balas
avatar

ip sudah di cek konek. api juga udah, tetep gan gabisa. kenapa ya ?

Balas
avatar

di logcatnya gini gan "HTTP FAILED: java.net.SocketTimeoutException: failed to connect to /192.168.43.140 (port 80) after 60000ms" minta pencerahannya gan.

Balas
avatar

coba di cek sinyal internet agan mungkin, lampirkan aja screenshot sama logcatnya di sini

Balas
avatar

PrefUtil.putUser(LoginActivity.this, PrefUtil.USER_SESSION, user);

gan saya ada merah di user nya kenapa ya? padahal sudah sama
tulisan erornya wrong 3rd argument

Balas
avatar

coba cek PrefUtil gan mungkin ada yg salah

Balas
avatar

gan mau tanya dong, ketika sudah selesai coding semua dan APK nya saya copy di hp, tiba tiba kok tidak bisa di run ya aplikasinya?? dan muncul tulisan "unfortunately, 'my apps' has stopped" mohon bimbingannya gan, masih newbie hehe

Balas
avatar

coba langsung di running di hp gan tanpa buat APK, lihat errornya di logcat

Balas
avatar

halo gan.

udah saya coba di xampp sama hosting gan, register tidak bisa.
kira2 salahnya dimana ya?
config sudah benar

Balas
avatar

errornya dmna gan? pastikan dulu host sama url sudah bener dan bisa diakses gan

Balas
avatar

nah permasalahannya, USB hp saya tidak ke-detect di android studio saya gan. untuk OS nya juga sudah sesuai spesifikasi minimum. saya pakek android studio 2.3 dan hp Asus Zenfone 2 Z00AD. apakah ada masalah dengan itu?

Balas
avatar

wah harus dikoneksikan USB hp gan soalnya kalo gak gitu susah detect errornya dimana. Coba agan searching lagi cara koneksi ke hp asus zenfone 2, mungkin USB drivernya belum terinstall..

Balas
avatar

gan kenapa ya pas klik login aplikasi langsung keluar?

Balas
avatar

gan kok saya running gak bisa ada pesan An error occurred! tolong solusinya gan

Balas
avatar

cek koneksi internet agan dan koneksi ke localhost mungkin blm terkoneksi...

Balas
avatar

bro, mau nanya ni bro
ko pada saat login mala keluar appnya, apanya yg sala tu bro..?

Balas
avatar

coba lihat di logcat trs SS errornya gan

Balas
This comment has been removed by the author. - Hapus
avatar

maf bro file jsonnya udh diruba kaya gini, maunya login hanya dengan menggunakan No indik.


FALSE);
if (isset($_POST['nim'])) {
$nim = htmlspecialchars($_GET['nim']);
//$encrypted_password = hash("sha256", $password);// encrypted password
$sql = $MySQLiconn->query("SELECT * FROM mhasiswa WHERE nim='$nim'");

if(mysqli_num_rows($sql) > 0){
while($row = $sql->fetch_array()){
$response["error"] = FALSE;
$response["message"] = "Login Successfull";
$response["data"]["nim"] = $row['nim'];
$response["data"]["nama"] = $row['nama'];
$response["data"]["kelas"] = $row['kelas'];
$response["data"]["alamat"] = $row['alamat'];
$response["data"]["tempat_lahir"] = $row['tempat_lahir'];
$response["data"]["kelamin"] = $row['kelamin'];
$response["data"]["agama"] = $row['agama'];
//$response["data"]["jurusan"] = $row['jurusan'];
}

echo json_encode($response);
}else{
$response["error"] = TRUE;
$response["message"] = "Incorrect nim ";

echo json_encode($response);
}
}

?>

Balas
avatar

ini file lgin,java, udah benar blum..?


if(isSessionLogin()) {
Profil.start(this);
Login.this.finish();
}
btnLogin = (Button) findViewById(R.id.login);
nimText = (EditText) findViewById(R.id.nim);

btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
loginAct();
}
});

}

void loginAct() {
String nim = nimText.getText().toString();
//String password = passwordText.getText().toString();

if(TextUtils.isEmpty(nim)) {
nimText.setError("Nim cannot be empty!");
return;
}

//if(TextUtils.isEmpty(password)) {
// passwordText.setError("Password cannot be empty");
// return;
//}

loginService = new LoginService(this);
loginService.doLogin(nim, new Callback() {
@Override
public void onResponse(Call call, Response response) {
User user = (User) response.body();

if(user != null) {
if(!user.isError()) {
PrefUtil.putUser(Login.this, PrefUtil.USER_SESSION, user);
Profil.start(Login.this);
Login.this.finish();
}

Toast.makeText(Login.this, user.getMessage(), Toast.LENGTH_SHORT).show();
}
}

@Override
public void onFailure(Call call, Throwable t) {
Toast.makeText(Login.this, "An error occurred!", Toast.LENGTH_SHORT).show();
}
});
}

Balas
This comment has been removed by the author. - Hapus
avatar

ada bbrp file yg hrus dirubah kalo gitu gan pertama di :
1. LoginInterface.java
ganti field email dgn nim

@FormUrlEncoded
@POST(Config.API_LOGIN)
Call login(
@Field("nim") String nim,
@Field("password") String password);

2. UserData.java
nama variabel atau atribut di kelas UserData harus sama dgn respon JSON agan

public class UserData {

private String nim;
private String nama;
private String kelas;
private String alamat;
private String tempat_lahir;
private String kelamin;
private String agama;

public UserData() {
}

public String getNim() {
return nim;
}

public void setNim(String nim) {
this.nim = nim;
}

public String getNama() {
return nama;
}

public void setNama(String nama) {
this.nama = nama;
}

public String getKelas() {
return kelas;
}

public void setKelas(String kelas) {
this.kelas = kelas;
}

public String getAlamat() {
return alamat;
}

public void setAlamat(String alamat) {
this.alamat = alamat;
}

public String getTempatLahir() {
return tempat_lahir;
}

public void setTempatLahir(String tempat_lahir) {
this.tempat_lahir = tempat_lahir;
}

public String getKelamin() {
return kelamin;
}

public void setKelamin(String kelamin) {
this.kelamin = kelamin;
}

public String getAgama) {
return agama;
}

public void setAgama(String agama) {
this.agama = agama;
}
}

Balas
This comment has been removed by the author. - Hapus
This comment has been removed by the author. - Hapus
avatar

udh diubah semua..
tp masi keluar

tp info logcatnya..
FATAL EXCEPTION: main
ava.lang.NoClassDefFoundError: okhttp3.internal.DiskLruCache$4
at okhttp3.internal.DiskLruCache.(DiskLruCache.java:799)
at okhttp3.Cache.(Cache.java:182)
at okhttp3.Cache.(Cache.java:178)

okhttp3nya error, padahal udh diimport yg sama, trus gimna mas, apa sy harus ganti versi okhttpnya..?

Balas
avatar

import librarynya spti di gradle gan, yg diimport ini aja :

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

trus perhatikan import di kelas java contohnya di class RetrofitBuilder spti ini
import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;

jgn lupa clean dan build..
kalau tetap gak bisa coba download projectnya aja di https://github.com/wimsonevel/AndroidLoginAndRegistration

Balas
avatar

permisi mau nanya kenapa ya registrasi nya kok nggak bisa jalan

Balas
avatar

pastikan terkoneksi dulu dngn localhost gan

Balas
avatar

Kayanya belum dijelaskan bagaimana menampilkan halaman Login ya. Di Manifest harus ada yang di edit bukan?

Balas
avatar

Punya saya kok Invalid Username and Password ya gan? Padahal udah bener

Balas
avatar

belum gan nanti sy revisi artikelnya.. source code lengkapnya bisa dilihat https://github.com/wimsonevel/AndroidLoginAndRegistration

Balas
avatar

mungkin ada step2 yg terlewatkan gan

Balas
avatar

Saya pake source code punya agan yang di github...saya coba registrasi juga gagal.
Ini log di monitor pas saya registrasi:

08-24 00:17:39.534 20084-20719/com.wimso.androidloginandregistration D/OkHttp: --> POST http://192.168.56.1/simple_api/register.php http/1.1
08-24 00:17:39.534 20084-20719/com.wimso.androidloginandregistration D/OkHttp: Content-Type: application/x-www-form-urlencoded
08-24 00:17:39.534 20084-20719/com.wimso.androidloginandregistration D/OkHttp: Content-Length: 69
08-24 00:17:39.534 20084-20719/com.wimso.androidloginandregistration D/OkHttp: firstname=john&lastname=doe&email=johndoe%40gmail.com&password=qweqwe
08-24 00:17:39.534 20084-20719/com.wimso.androidloginandregistration D/OkHttp: --> END POST (69-byte body)
08-24 00:17:39.598 20084-20719/com.wimso.androidloginandregistration D/OkHttp: <-- 200 OK http://192.168.56.1/simple_api/register.php (63ms)
08-24 00:17:39.598 20084-20719/com.wimso.androidloginandregistration D/OkHttp: Date: Thu, 24 Aug 2017 04:17:41 GMT
08-24 00:17:39.598 20084-20719/com.wimso.androidloginandregistration D/OkHttp: Server: Apache/2.4.26 (Win32) OpenSSL/1.0.2l PHP/7.1.7
08-24 00:17:39.598 20084-20719/com.wimso.androidloginandregistration D/OkHttp: X-Powered-By: PHP/7.1.7
08-24 00:17:39.598 20084-20719/com.wimso.androidloginandregistration D/OkHttp: Content-Length: 241
08-24 00:17:39.598 20084-20719/com.wimso.androidloginandregistration D/OkHttp: Keep-Alive: timeout=5, max=100
08-24 00:17:39.598 20084-20719/com.wimso.androidloginandregistration D/OkHttp: Connection: Keep-Alive
08-24 00:17:39.598 20084-20719/com.wimso.androidloginandregistration D/OkHttp: Content-Type: text/html; charset=UTF-8
08-24 00:17:39.599 20084-20719/com.wimso.androidloginandregistration D/OkHttp: <-- END HTTP (binary 241-byte body omitted)
08-24 00:17:39.687 20084-20124/com.wimso.androidloginandregistration W/EGL_emulation: eglSurfaceAttrib not implemented
08-24 00:17:39.687 20084-20124/com.wimso.androidloginandregistration W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xeb96c220, error=EGL_SUCCESS
08-24 00:17:39.745 20084-20124/com.wimso.androidloginandregistration V/RenderScript: 0xe238ac00 Launching thread(s), CPUs 4

Mungkin tau? Makasih sebelumnya

Balas
avatar

Halo Mas, saya baru aajb elajar android. Ngeliat tutorial ini saya mulai sedikit ngeh apa itu android. Agak beda dengan html yah :p

Saya mau tanya dong, itu pengaturan mainactivity, loginAct dan RegisterAct itu dimana yah? Kalo sama mau custom, let sat saya mau tambaghin 1 service lagi, itu gimaan yah>?

Balas
avatar

ijin sedot gan :D sangat bermanfaat ilmunya :)

Balas
avatar

Permisi gan mau tanya, di bagian LoginACtivity saya masih ada yang salah di

@Override
public void onClick(View view) {
RegisterActivity.start(LoginActivity.this);
}
Bagian Start nya masih merah

if(!user.isError()) {

User nya merah

Toast.makeText(LoginActivity.this, user.getMessage(), Toast.LENGTH_SHORT).show();

user.getMessage() nya juga merah
Semuanya tertulis Cannot find symbol method

Balas
avatar

Mas saya mau tanya aku run programnya dengan menggunakan usb debuglangsung di hp
Itu ko msh ga bza
Udh muncul aplikasinya di hp di klik ada pesan force wait usb debug proses

Balas
avatar

cara tau sudah terkoneksi dengan database gmna ya?

Balas
avatar

Mas, mau nanya kalau kita pakai WAMP bagaimana settingannya?.

Balas
This comment has been removed by the author. - Hapus
avatar

kang,. android:padding @dimen error semua,. itu gimana?

Balas
avatar

Gan, saya sudah download projectnya tapi pas klik register belum masuk ke database.
logcatnya seperti ini :
11-24 10:36:59.918 7982-8360/com.wimso.androidloginandregistration D/OkHttp: --> POST http://10.10.30.251/simple_api/register.php http/1.1
11-24 10:36:59.918 7982-8360/com.wimso.androidloginandregistration D/OkHttp: Content-Type: application/x-www-form-urlencoded
11-24 10:36:59.919 7982-8360/com.wimso.androidloginandregistration D/OkHttp: Content-Length: 71
11-24 10:36:59.919 7982-8360/com.wimso.androidloginandregistration D/OkHttp: firstname=ari&lastname=yudianto&email=ariyu%40gmail.com&password=123456
11-24 10:36:59.920 7982-8360/com.wimso.androidloginandregistration D/OkHttp: --> END POST (71-byte body)
11-24 10:36:59.921 7982-8360/com.wimso.androidloginandregistration D/libc-netbsd: [getaddrinfo]: mtk hostname=10.10.30.251; servname=(null); netid=0; mark=0
11-24 10:36:59.921 7982-8360/com.wimso.androidloginandregistration D/libc-netbsd: getaddrinfo( app_uid:10183
11-24 10:36:59.921 7982-8360/com.wimso.androidloginandregistration D/libc-netbsd: getaddrinfo() uid prop:
11-24 10:36:59.921 7982-8360/com.wimso.androidloginandregistration D/libc-netbsd: getaddrinfo() getuid():10183
11-24 10:36:59.921 7982-8360/com.wimso.androidloginandregistration D/libc-netbsd: [getaddrinfo]: mtk ai_addrlen=0; ai_canonname=(null); ai_flags=4; ai_family=0
11-24 10:36:59.930 7982-8360/com.wimso.androidloginandregistration I/System.out: [CDS][DNS] getAllByNameImpl netId = 0
11-24 10:36:59.931 7982-8360/com.wimso.androidloginandregistration D/libc-netbsd: [getaddrinfo]: mtk hostname=10.10.30.251; servname=(null); netid=0; mark=0
11-24 10:36:59.931 7982-8360/com.wimso.androidloginandregistration D/libc-netbsd: getaddrinfo( app_uid:10183
11-24 10:36:59.931 7982-8360/com.wimso.androidloginandregistration D/libc-netbsd: getaddrinfo() uid prop:
11-24 10:36:59.931 7982-8360/com.wimso.androidloginandregistration D/libc-netbsd: getaddrinfo() getuid():10183
11-24 10:36:59.931 7982-8360/com.wimso.androidloginandregistration D/libc-netbsd: [getaddrinfo]: mtk ai_addrlen=0; ai_canonname=(null); ai_flags=4; ai_family=0
11-24 10:36:59.932 7982-8360/com.wimso.androidloginandregistration I/System.out: [CDS]rx timeout:60000
11-24 10:36:59.932 7982-8360/com.wimso.androidloginandregistration I/System.out: [socket][2] connection /10.10.30.251:80;LocalPort=34897(60000)
11-24 10:36:59.932 7982-8360/com.wimso.androidloginandregistration I/System.out: [CDS]connect[/10.10.30.251:80] tm:60
11-24 10:36:59.933 7982-8360/com.wimso.androidloginandregistration D/Posix: [Posix_connect Debug]Process com.wimso.androidloginandregistration :80

Balas
avatar

Gan, sudah bisa register dan login sekarang. terima kasih tutorialnya sangant membantu saya yang masih pemula.

Balas
avatar

gmna caranya pak..? bisa bantu saya..?

Balas
avatar

min ini bisa register cuman satu user ya ?

Balas
avatar

kalo "register failure" itu knapa ya gan?

Balas
avatar

kak kenapa waktu login muncul toast incorrect Email or Password
sama register muncul toast an error occurred?

Balas
avatar

ini dimana y gan erornya 04-05 00:19:02.680 14273-14273/? I/DigitalWidgetProvider: onReceive: Intent { act=android.intent.action.TIME_SET flg=0x25200010 cmp=com.google.android.deskclock/com.android.alarmclock.DigitalAppWidgetProvider }
04-05 00:19:02.684 1635-1648/? E/memtrack: Couldn't load memtrack module
04-05 00:19:02.684 1635-1648/? W/android.os.Debug: failed to get memory consumption info: -1
04-05 00:19:02.735 14273-14273/? I/DigitalWidgetProvider: onReceive: Intent { act=com.android.deskclock.ALARM_CHANGED flg=0x10 cmp=com.google.android.deskclock/com.android.alarmclock.DigitalAppWidgetProvider }
04-05 00:19:03.584 1635-1654/? W/RemoteFillService: Not handling { when=-6ms what=3 target=com.android.internal.os.HandlerCaller$MyHandler } as service for ComponentInfo{com.google.android.gms/com.google.android.gms.autofill.service.AutofillService} is already destroyed
04-05 00:19:04.028 11028-11692/? I/EventLogSendingHelper: Sending log events.
04-05 00:19:07.214 1635-1648/? E/memtrack: Couldn't load memtrack module
04-05 00:19:07.214 1635-1648/? W/android.os.Debug: failed to get memory consumption info: -1
04-05 00:19:07.605 1408-1408/? I/qemu-props: start adbd ...

Balas
avatar

mas kalo mau setelah login nampilin datanya pake fragment gmna mas ?

Balas
avatar

kak mau tanya, itu bikin data yg di model dari mana ya? soalnya saya coba running di postman service login maupun register tidak ada menampilkan responsenya

Balas
avatar

kenapa eror pada LoginActivity "cannot resolve method isError()???

Balas
avatar

model user itu didapat dari mana ya?

Balas
avatar

harusnya ada gan, gagal atau gaknya pasti munculin respon.. mungkin ada bagian codingan yg kurang lengkap, coba cek lagi...

Balas
avatar

dari respon json jika berhasil login

Balas
avatar

pas register kok an error occured ya gan? help

Balas
avatar

gak terkoneksi ke API nya gan, coba cek dulu

Balas
avatar

Nice mantap kang..
satu lagi di LoginActivity Error yang "cannot resolve method isError()" kenapa yaa

Balas
avatar

cek di class BaseResponse gan apakah udah bikin method isError() apa blum

Balas
avatar

sore gan, saya mau tanya..

ketika melakukan register knapa sllu muncul an error occured!
saya liat di pertanyaan di atas agan sllu kasih jawaban untuk cek API dan koneksi API nya.

saya udah cek gan kalo koneksi ke database nya sudah berhasil.

dan error yang an error occured! ini message nya dari project android studio.

apa ada lagi gan yang perlu di cek ?


thanks

Balas
avatar

kalo agan perhatikan di LoginActivity atau RegisterActivity errornya emg berasal dari onFailure, masalahnya mungkin di Base URL yg IP address gak terkoneksi.. coba pake IP Localhost, jika masih gagal saran saya pake hostingan aja...

Balas
avatar

kalo misalkan tidak terkoneksi harusnya tidak bisa login gan. saya buat user secara manual di database untuk login. dan itu berhasil untuk login berarti koneksinya kan connect yaa, nah pas mau regist gabisa dengan error message sprti yang saya infokan di atas gan.

Balas
avatar

mas, kalo errornya pas bagoan R doang merah gitu solusinya gimana gan ?
misal codingannya gini
setContentView(R.layout.activity_main);
});

nah, yg merah cuma R doang

Balas
avatar

Gan ini pake Android Studio versi berapa ya.? saya pakai Android Studio Versi 3 banyak yang error. mksh

Balas
avatar

cara mengatasi tidak terkoneksinya api gimana mas?, aku selalu an error occured. mohon pencerahannya aku masih newbie

Balas
avatar

saat ini belum ada waktu gan, nanti saya bikinin tutorial yang baru

Balas
avatar

kenapa ya programnya pas di jalankan gak bisa malah ada bacaan "An error occured!" padahal sudah sesuai dengan tutorial dan programnya tidak ada yang eror

Balas
This comment has been removed by the author. - Hapus
avatar

database sudah buat . file .php juga sudah test terkoneksi . ip sudah sama dengan yang di pc . apk jalan tapi registrasi / login pun gagal terus . tolong bantuannya gan.??
apa gara" saya pakai xampp portable.

Balas
avatar

jadi gan mau login dengan nama dan password, ketika klik tombol login logcat LoginService error.

Balas
avatar

#LoginService.java

package com.example.zefatani.network;
import android.content.Context;
import com.example.zefatani.network.interfaces.LoginInterface;
import com.example.zefatani.network.config.RetrofitBuilder;
import retrofit2.Callback;
public class LoginService {

private LoginInterface loginInterface;
public LoginService(Context context){
loginInterface = RetrofitBuilder.builder(context)
.create(LoginInterface.class);
}
public void doLogin(String nama, String password, Callback callback){
loginInterface.login(nama, password).enqueue(callback);
}
}

Balas
avatar

#Method LoginAct

void loginAct(){
String nama = Editusername.getText().toString();
String password = Editpassword.getText().toString();
if(nama.isEmpty()) {
Toast.makeText(getApplicationContext(), "Username Cannot be empty", Toast.LENGTH_LONG).show();
return;
}
if(password.isEmpty()) {
Toast.makeText(getApplicationContext(), "Password Cannot be empty", Toast.LENGTH_LONG).show();
return;
}
loginService = new LoginService(this);
loginService.doLogin(nama, password, new Callback() {
@Override
public void onResponse(Call call, Response response) {
User user = (User) response.body();
if (user !=null){
if (!user.isError()){
PrefUtil.putUser(login.this, PrefUtil.USER_SESSION, user);
form_home.start(login.this);
login.this.finish();
}
Toast.makeText(login.this, user.getMessage(), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call call, Throwable t) {
Toast.makeText(login.this, "An error occurred!", Toast.LENGTH_SHORT).show();
}
});
}
boolean isSessionLogin() {
return PrefUtil.getUser(this, PrefUtil.USER_SESSION) != null;
}

Balas
avatar

#Login.php

FALSE);

if (isset($_POST['nama']) && isset($_POST['password'])) {

$nama = htmlspecialchars($_POST['nama']);
$password = htmlspecialchars($_POST['password']);

$encrypted_password = hash("sha256", $password);// encrypted password

$sql = $MySQLiconn->query("SELECT * FROM tbl_pengguna WHERE nama='$nama' AND password='$password'");

if(mysqli_num_rows($sql) > 0){
while($row = $sql->fetch_array()){
$response["error"] = FALSE;
$response["message"] = "Login Successfull";
$response["data"]["no_hp"] = $row['no_hp'];
$response["data"]["nama"] = $row['nama'];
$response["data"]["alamat"] = $row['alamat'];
}

echo json_encode($response);
}else{
$response["error"] = TRUE;
$response["message"] = "Incorrect Email or Password!";

echo json_encode($response);
}
}
?>

Balas
avatar

#Config.java

package com.example.zefatani.network.config;
public class Config {
public static final String BASE_URL ="https://zefatani.000webhostapp.com";
public static final String API_URL = BASE_URL + "/zefatani";
public static final String API_LOGIN = API_URL +"/login.php";
public static final String API_REGISTER =API_URL +"/register.php";
}

Balas
avatar

Mohon Bantuannya, Terima Kasih :)

Balas
avatar

Mas. Ini kenapa ya gagal terus pas register. Keterangannya register failure, dan saya coba masukin manual datanya pas coba login juga username dan password salah.. mohon bantuannya mas, terimakasih :)

Balas
avatar

Sudah berhasil mas haha Thanks

Balas
avatar

Gan, di file config.Java yg pake ip itu sudah sy ganti dengan localhost, tp kok msh blm bisa ya?

Balas
avatar

Mas ini kenapa di bagian LoginActivity , MainActivity , RegisterActivity coding saya error di bagian R.Layout itu error . an itu maksudnya apa ?

Balas
avatar

mas error mas ada peringatan sperti ini :

An Error Occured

<i rel="image>file:///C:/Users/ADIT/Documents/Lightshot/Screenshot_5.png</i>

Balas
avatar

gan cara debug apk ke android lewat macintosh ipnya ceknya dimana gan ?

Balas
avatar

ini menjalankan khusu dibemulator atau bisa juga di android.
kalau menjalankan program lewat debuging di android ini memoengaruhi login dan register ga mas. soalnya tidak bisa di masuk ke login dan register

Balas
avatar

Permisi mas, mau tanya. Untuk syntax ini body nya kok masih merah itu kenapa ya? terimakasih

@Override
public void onResponse(Call call, Response response) {
User user = (User) response.body();

Balas
avatar

yang masih blm bs login dan daftar krn " An error occurred! "
coba tambahkan di manifestnya ini nii : android:usesCleartextTraffic="true"




...

Balas
This comment has been removed by the author. - Hapus
avatar

error di import com.wimso.androidloginandregistration.BuildConfig;
di file RetrofitBuilder.java

Balas
avatar

Halo kak, terimakasih artikelnya... ini sangat membantu saya dalam menyelesaikan tugas kuliah saya. oh ya kak, perkenalkan nama saya Nurhamimah dan jangan lupa kunjungi website kampus saya ISB Atma Luhur

Balas
avatar

Halo kak, terimakasih artikelnya... ini sangat membantu saya dalam menyelesaikan tugas kuliah saya. oh ya kak, perkenalkan nama saya Nurhamimah dan jangan lupa kunjungi website kampus saya ISB Atma Luhur

Balas

Penulisan markup di komentar
  • Silakan tinggalkan komentar sesuai topik. Komentar yang menyertakan link aktif, iklan, atau sejenisnya akan dihapus.
  • Untuk menyisipkan kode gunakan <i rel="code"> kode yang akan disisipkan </i>
  • Untuk menyisipkan kode panjang gunakan <i rel="pre"> kode yang akan disisipkan </i>
  • Untuk menyisipkan quote gunakan <i rel="quote"> catatan anda </i>
  • Untuk menyisipkan gambar gunakan <i rel="image"> URL gambar </i>
  • Untuk menyisipkan video gunakan [iframe] URL embed video [/iframe]
  • Kemudian parse kode tersebut pada kotak di bawah ini
  • © 2015 Simple SEO ✔

Ads