Membuat Form Register dan Login Android, dengan menggunakan Php Mysql

Pada pertemuan pertama, kita akan membahas pembuatan form register dan login yang terkoneksi dengan database mysql dan file php.
Tanpa basa basi langsung saja kita mulai, pertama-tama persiapkan XAMPP terlebih dahulu untuk membuat dan menyimpan database user. Jika aplikasi tersebut telah diinstal maka buatlah database user tersebut. Berikut langkah-langkah membuat database :
  1. Buka XAMPP
  2. Buka localhost/phpmyadmin pada browser
  3. Buat database create database
  4. Buat kolom sesuai data yang dibutuhkan seperti username, password, email, dll.
Setelah database dibuat selanjutnya buatlah form login, register dan koneksi database dengan bahasa pemrograman php.
Masukkan source code login.php sebagai berikut
<?php
//load and connect to MySQL database stuff
require(“config.inc.php”);if (!empty($_POST)) {
//gets user’s info based off of a username.
$query = “SELECT id,username,password FROM users WHERE username = :username”; 
$query_params = array(‘:username’ => $_POST[‘username’]);
try {
$stmt   = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die(“Failed to run query: ” . $ex->getMessage());

//or just use this use this one to product JSON data:
$response[“success”] = 0;
$response[“message”] = “Database Error1. Please Try Again!”;
die(json_encode($response));

}

//This will be the variable to determine whether or not the user’s information is correct.
//we initialize it as false.

$validated_info = false;
//fetching all the rows from the query
$row = $stmt->fetch();
if ($row) {
//if we encrypted the password, we would unencrypt it here, but in our case we just
//compare the two passwords
if ($_POST[‘password’] === $row[‘password’]) {
$login_ok = true;
}
}
else{
$login_ok = false;
}

// If the user logged in successfully, then we send them to the private members-only page
// Otherwise, we display a login failed message and show the login form again
//if ($login_ok) {
if ($login_ok) {
$response[“success”] = 1;
$response[“message”] = “Login successful!”;
die(json_encode($response));
} else {
$response[“success”] = 0;
$response[“message”] = “Login gagal!”;
die(json_encode($response));
}
} else {
?>
<h1>Login</h1>
<form action=”login.php” method=”post”>
Username:<br />
<input type=”text” name=”username” placeholder=”username” />
<br /><br />
Password:<br />
<input type=”password” name=”password” placeholder=”password” value=”” />
<br /><br />
<input type=”submit” value=”Login” />
</form>
<a href=”register.php”>Register</a>
<?php
}

?>

Masukkan source code register.php sebagai berikut
<?php

require(“config.inc.php”);

//if posted data is not empty
if (!empty($_POST)) {

if (empty($_POST[‘username’]) || empty($_POST[‘password’]) || empty($_POST[’email’])) {


// Create some data that will be the JSON response
$response[“success”] = 0;
$response[“message”] = “Tolong Inputkan Semuanya.”;

die(json_encode($response));
}

$query        = ” SELECT 1 FROM users WHERE username = :user”;
$query_params = array(‘:user’ => $_POST[‘username’]);

try {
$stmt   = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {

$response[“success”] = 0;
$response[“message”] = “Database Error1. Please Try Again!”;
die(json_encode($response));
}

$row = $stmt->fetch();
if ($row) {

$response[“success”] = 0;
$response[“message”] = “I’m sorry, this username is already in use”;
die(json_encode($response));
}

$query = “INSERT INTO users ( username, password, email ) VALUES ( :user, :pass, :mail ) “;
$query_params = array(
‘:user’ => $_POST[‘username’],
‘:pass’ => $_POST[‘password’],
‘:mail’  => $_POST[’email’]
);

//time to run our query, and create the user
try {
$stmt   = $db->prepare($query);
$result = $stmt->execute($query_params);

$response[“success”] = 1;
$response[“message”] = “Username Successfully Added!”;
echo json_encode($response);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die(“Failed to run query: ” . $ex->getMessage());

//or just use this use this one:
$response[“success”] = 0;
$response[“message”] = “Database Error2. Please Try Again!”;
die(json_encode($response));
}



//for a php webservice you could do a simple redirect and die.
//header(“Location: login.php”);
//die(“Redirecting to login.php”);


} else {
?>
<h1>Register</h1>
<form action=”register.php” method=”post”>
Username:<br /> <input type=”text” name=”username” value=”” />
<br /><br />
Password:<br /> <input type=”password” name=”password” value=”” />
<br /><br />
Email: <br /> <input type=”text” name=”email” value=”” />
<br /><br />
<input type=”submit” value=”Register New User” />
<a href=”login.php”>Login!</a>
</form>
<?php
}

?>
Masukkan Source code config.inc.php untuk koneksi ke database
<?php

$username = “root”;
$password = “”;
$host = “localhost”;
$dbname = “webservice”;

$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => ‘SET NAMES utf8’);

try
{
$db = new PDO(“mysql:host={$host};dbname={$dbname};charset=utf8”, $username, $password, $options);
}
catch(PDOException $ex)
{
die(“Failed to connect to the database: ” . $ex->getMessage());
}

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

if(function_exists(‘get_magic_quotes_gpc’) && get_magic_quotes_gpc())
{
function undo_magic_quotes_gpc(&$array)
{
foreach($array as &$value)
{
if(is_array($value))
{
undo_magic_quotes_gpc($value);
}
else
{
$value = stripslashes($value);
}
}
}

undo_magic_quotes_gpc($_POST);
undo_magic_quotes_gpc($_GET);
undo_magic_quotes_gpc($_COOKIE);
}

header(‘Content-Type: text/html; charset=utf-8’);

session_start();

?>

Setelah database dan form php telah dibuat maka yang harus dilakukan adalah membuat aplikasi android langsung dengan menggunakan eclipse. Dalam artikel ini saya menggunakan aplikasi android yang sebelumnya pernah dibuat dan dijelaskan pada tutorial sebelumnya. Buka android project tersebut kemudian buatlah class baru dengan nama JSONParser.java.
Masukkan source kode berikut pada class JSONParser.java
package app.agung.smartshopper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = “”;

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {

// Making HTTP request
try {

// check for request method
if(method == “POST”){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

}else if(method == “GET”){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, “utf-8”);
url += “?” + paramString;
HttpGet httpGet = new HttpGet(url);

HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, “iso-8859-1”), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + “\n”);
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e(“Buffer Error”, “Error converting result ” + e.toString());
}

// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e(“JSON Parser”, “Error parsing data ” + e.toString());
}

// return JSON String
return jObj;

}
}

Selanjutnya buatlah activity baru dengan cara klik kanan new > other>android activity.
Beri nama activity tersebut dengan Login. Kemudian bukalah class login tersebut dan masukkan source code berikut ini
package app.agung.smartshopper;

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

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import app.agung.smartshopper.JSONParser;
import app.agung.smartshopper.Login;
import app.agung.smartshopper.R;
import app.agung.smartshopper.Register;
import app.agung.smartshopper.Login.AttemptLogin;

import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


public class Login extends Activity implements OnClickListener{

private EditText user, pass;
//private EditText urlserver;
private Button mSubmit, mRegister;

// Progress Dialog
private ProgressDialog pDialog;

// JSON parser class
JSONParser jsonParser = new JSONParser();

//php login script location:

//localhost :
//testing on your device
//put your local ip instead,  on windows, run CMD > ipconfig
//or in mac’s terminal type ifconfig and look for the ip under en0 or en1
//private static final String LOGIN_URL = “http://xxx.xxx.x.x:1234/webservice/login.php”;

//testing on Emulator:
private static final String LOGIN_URL =  “http://192.168.1.8/webservice/login.php”;

//testing from a real server:
//private static final String LOGIN_URL = “http://www.yourdomain.com/webservice/login.php”;

//JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = “success”;
private static final String TAG_MESSAGE = “message”;

@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);

//setup input fields
user = (EditText)findViewById(R.id.username);
pass = (EditText)findViewById(R.id.password);

//setup buttons
mSubmit = (Button)findViewById(R.id.login);
mRegister = (Button)findViewById(R.id.register);

//register listeners
mSubmit.setOnClickListener(this);
mRegister.setOnClickListener(this);

}

@Override
public void onClick(View v) {

switch (v.getId()) {
case R.id.login:
new AttemptLogin().execute();
break;
case R.id.register:
Intent i = new Intent(this, Register.class);
startActivity(i);
break;

default:
break;
}
}

class AttemptLogin extends AsyncTask<String, String, String> {

boolean failure = false;

@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage(“Attempting login…”);
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}

@Override
protected String doInBackground(String… args) {
// Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
//String urlll = urlserver.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(“username”, username));
params.add(new BasicNameValuePair(“password”, password));

Log.d(“request!”, “starting”);
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, “POST”, params);

// check your log for json response
Log.d(“Login attempt”, json.toString());

// json success tag
//success = 5;
String status;
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
status= “sukses”;
Log.d(“Login Successful!”, json.toString());
Intent i = new Intent(Login.this,MainActivity.class);
i.putExtra(“param” , status);
i.putExtra(“nama”, username);
finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
}else{
status= “gagal”;
Log.d(“Login Failure!”, json.toString());
Intent a = new Intent(Login.this,Login.class);
a.putExtra(“param” , status);
a.putExtra(“nama”, username);
finish();
startActivity(a);
return json.getString(TAG_MESSAGE);

//            return json.getString(TAG_MESSAGE);

}
} catch (JSONException e) {
e.printStackTrace();
}

return null;

}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(Login.this, file_url, Toast.LENGTH_SHORT).show();
}

}

}


}

Selanjutnya menuju ke layout aplikasi buka activity_login.xml dan buatlah layout seperti ini


Untuk membuat tampilan seperti diatas berikut ini source codenya
<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”
tools:context=“app.agung.smartshopper.Login” >

<TextView
android:id=“@+id/textView1”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
        android:text=“Welcome Smartshopper”
android:textAppearance=“?android:attr/textAppearanceMedium” />

<TextView
android:id=“@+id/textView2”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_alignLeft=“@+id/textView1”
android:layout_below=“@+id/textView1”
android:layout_marginTop=“19dp”
android:text=“Silahkan Login terlebih dahulu..” />

<TextView
android:id=“@+id/textView3”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_alignLeft=“@+id/textView2”
android:layout_below=“@+id/textView2”
android:layout_marginTop=“15dp”
        android:text=“Username”
android:textAppearance=“?android:attr/textAppearanceMedium” />

<EditText
android:id=“@+id/username”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_alignLeft=“@+id/textView3”
android:layout_below=“@+id/textView3”
android:ems=“10”
android:inputType=“textPersonName” >

<requestFocus />
</EditText>

<EditText
android:id=“@+id/password”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_alignLeft=“@+id/textView4”
android:layout_below=“@+id/textView4”
android:ems=“10”
android:inputType=“textPassword” />

<Button
android:id=“@+id/register”
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”
android:layout_alignLeft=“@+id/login”
android:layout_below=“@+id/login”
android:layout_marginTop=“60dp”
        android:text=“Register” />

<TextView
android:id=“@+id/textView5”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_alignLeft=“@+id/register”
android:layout_below=“@+id/login”
android:layout_marginTop=“41dp”
android:text=“Belum punya akun? Silahkan Daftar disini..” />

<Button
android:id=“@+id/login”
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”
android:layout_alignLeft=“@+id/username”
android:layout_below=“@+id/username”
android:layout_marginTop=“77dp”
android:text=“Login” />

<TextView
android:id=“@+id/textView4”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_alignRight=“@+id/textView3”
android:layout_below=“@+id/username”
android:text=“Password”
android:textAppearance=“?android:attr/textAppearanceMedium” />

</RelativeLayout>


Selesai sudah pembuatan form login maka sekarang kita membuat form registrasi dengan membuat activity baru seperti cara sebelumnya. Langsung saja buka class register.java dan masukkan source code sebagai berikut.
package app.agung.smartshopper;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import app.agung.smartshopper.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Register extends Activity implements OnClickListener{

private EditText user, pass, mail;
private Button  mRegister;

// Progress Dialog
private ProgressDialog pDialog;

// JSON parser class
JSONParser jsonParser = new JSONParser();

//php login script

//localhost :
//testing on your device
//put your local ip instead,  on windows, run CMD > ipconfig
//or in mac’s terminal type ifconfig and look for the ip under en0 or en1
// private static final String LOGIN_URL = “http://xxx.xxx.x.x:1234/webservice/register.php”;

//testing on Emulator:
private static final String LOGIN_URL = “http://192.168.1.8/webservice/register.php”;

//testing from a real server:
//private static final String LOGIN_URL = “http://www.yourdomain.com/webservice/register.php”;

//ids
private static final String TAG_SUCCESS = “success”;
private static final String TAG_MESSAGE = “message”;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.register);

user = (EditText)findViewById(R.id.username);
pass = (EditText)findViewById(R.id.password);
mail = (EditText)findViewById(R.id.email);



mRegister = (Button)findViewById(R.id.register);
mRegister.setOnClickListener(this);

}

@Override
public void onClick(View v) {
new CreateUser().execute();

}

class CreateUser extends AsyncTask<String, String, String> {

/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;

@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Register.this);
pDialog.setMessage(“Creating User…”);
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}

@Override
protected String doInBackground(String… args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
String email            = mail.getText().toString();

try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(“username”, username));
params.add(new BasicNameValuePair(“password”, password));
params.add(new BasicNameValuePair(“email”, email));

Log.d(“request!”, “starting”);

//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, “POST”, params);

// full json response
Log.d(“Login attempt”, json.toString());

// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d(“User Created!”, json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d(“Login Failure!”, json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);

}
} catch (JSONException e) {
e.printStackTrace();
}

return null;

}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(Register.this, file_url, Toast.LENGTH_SHORT).show();
}

}

}
}

Jika sudah maka buatlah layout pada form register.xml ini dengan memasukkan source code berikut ini.
<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”
>

<EditText
android:id=“@+id/username”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_alignParentLeft=“true”
android:layout_alignParentRight=“true”
android:layout_below=“@+id/textView1”
android:ems=“10”
        android:hint=“username” >

<requestFocus />
</EditText>

<EditText
android:id=“@+id/password”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_alignParentLeft=“true”
android:layout_alignParentRight=“true”
android:layout_below=“@+id/TextView01”
android:ems=“10”
        android:hint=“password”
android:inputType=“textPassword” />

<TextView
android:id=“@+id/kiriman”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_alignParentTop=“true”
android:layout_centerHorizontal=“true”
android:layout_marginTop=“17dp”
android:gravity=“center”
        android:text=“Silahkan Isi Data Anda”
android:textAppearance=“?android:attr/textAppearanceLarge”
android:textStyle=“bold” />

<EditText
android:id=“@+id/email”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_alignParentLeft=“true”
android:layout_alignParentRight=“true”
android:layout_below=“@+id/textView3”
android:ems=“10”
android:hint=“email”
android:inputType=“textEmailAddress” >

</EditText>

<Button
android:id=“@+id/register”
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”
android:layout_alignParentLeft=“true”
android:layout_below=“@+id/email”
android:layout_marginTop=“18dp”
        android:text=“Register” />

<TextView
android:id=“@+id/textView3”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_alignLeft=“@+id/TextView01”
android:layout_below=“@+id/password”
android:layout_marginTop=“18dp”
android:text=“Email”
android:textSize=“16dp” />

<TextView
android:id=“@+id/TextView01”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_alignParentLeft=“true”
android:layout_below=“@+id/username”
android:layout_marginLeft=“18dp”
android:layout_marginTop=“21dp”
android:text=“Password”
        android:textSize=“16dp” />

<TextView
android:id=“@+id/textView1”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_alignLeft=“@+id/TextView01”
android:layout_below=“@+id/kiriman”
android:layout_marginTop=“20dp”
        android:text=“Username”
android:textSize=“16dp” />

</RelativeLayout>

Nah dengan demikian selesai sudah pembuatan form login dan register. Akan tetapi tentu saja artikel ini belum selesai, masih ada halaman utama dimana aplikasi ini akan berjalan setelah login. Maka pada main activity masukkan source code berikut.
<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”
>

<EditText
android:id=“@+id/username”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_alignParentLeft=“true”
android:layout_alignParentRight=“true”
android:layout_below=“@+id/textView1”
android:ems=“10”
        android:hint=“username” >

<requestFocus />
</EditText>

<EditText
android:id=“@+id/password”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_alignParentLeft=“true”
android:layout_alignParentRight=“true”
android:layout_below=“@+id/TextView01”
android:ems=“10”
        android:hint=“password”
android:inputType=“textPassword” />

<TextView
android:id=“@+id/kiriman”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_alignParentTop=“true”
android:layout_centerHorizontal=“true”
android:layout_marginTop=“17dp”
android:gravity=“center”
        android:text=“Silahkan Isi Data Anda”
android:textAppearance=“?android:attr/textAppearanceLarge”
android:textStyle=“bold” />

<EditText
android:id=“@+id/email”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_alignParentLeft=“true”
android:layout_alignParentRight=“true”
android:layout_below=“@+id/textView3”
android:ems=“10”
android:hint=“email”
android:inputType=“textEmailAddress” >

</EditText>

<Button
android:id=“@+id/register”
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”
android:layout_alignParentLeft=“true”
android:layout_below=“@+id/email”
android:layout_marginTop=“18dp”
        android:text=“Register” />

<TextView
android:id=“@+id/textView3”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_alignLeft=“@+id/TextView01”
android:layout_below=“@+id/password”
android:layout_marginTop=“18dp”
android:text=“Email”
android:textSize=“16dp” />

<TextView
android:id=“@+id/TextView01”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_alignParentLeft=“true”
android:layout_below=“@+id/username”
android:layout_marginLeft=“18dp”
android:layout_marginTop=“21dp”
android:text=“Password”
        android:textSize=“16dp” />

<TextView
android:id=“@+id/textView1”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_alignLeft=“@+id/TextView01”
android:layout_below=“@+id/kiriman”
android:layout_marginTop=“20dp”
        android:text=“Username”
android:textSize=“16dp” />

</RelativeLayout>

Setelah itu buatlah layout pada activity_main.xml dengan source code berikut
<LinearLayout xmlns:android=“http://schemas.android.com/apk/res/android”
xmlns:tools=“http://schemas.android.com/tools”
android:id=“@+id/LinearLayout1”
android:layout_width=“match_parent”
android:layout_height=“match_parent”
android:orientation=“vertical”
android:paddingBottom=“@dimen/activity_vertical_margin”
android:paddingLeft=“@dimen/activity_horizontal_margin”
android:paddingRight=“@dimen/activity_horizontal_margin”
android:paddingTop=“@dimen/activity_vertical_margin”
tools:context=“app.agung.smartshopper.MainActivity” >

<LinearLayout
android:layout_width=“match_parent”
android:layout_height=“26dp”
android:orientation=“horizontal” >

<Button
android:id=“@+id/logout”
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”
android:gravity=“right”
android:background=“@null”
android:text=“LogOut”
android:textColor=“#21dbd4” />
</LinearLayout>
<LinearLayout
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:orientation=“horizontal”>
<TextView
android:id=“@+id/hai”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_marginLeft=“23dp”
android:text=“Hallo…”
android:textSize=“20sp”
/>

<TextView
android:id=“@+id/usernm”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_marginLeft=“23dp”
android:text=“TextView”
android:textSize=“20sp” />

</LinearLayout>
<LinearLayout
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:orientation=“horizontal”>
<TextView
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
        android:text=“Masukkan harga Rp.”
android:layout_weight=“1” />

<EditText
android:id=“@+id/harga”
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:inputType=“number”
android:layout_weight=“1”>
</EditText>

</LinearLayout>

<LinearLayout
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:orientation=“horizontal”>
<TextView
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:text=“Masukkan Diskon %”
android:layout_weight=“1” />

<EditText
android:id=“@+id/diskon”
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:inputType=“number”
android:layout_weight=“1”>
</EditText>

</LinearLayout>

<Button
android:id=“@+id/Hitung”
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:gravity=“center_horizontal”
android:text=“Hitung!” />

<TextView
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:text=“Harga Setelah Diskon”
android:gravity=“center_horizontal” />

<EditText
android:id=“@+id/hargaDiskon”
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:gravity=“center_horizontal”
android:text=“Cek Hargamu disini”
android:textColor=“#ff3333”
android:textSize=“30sp”
android:editable=“false” />

<TextView
android:layout_width=“match_parent”
android:layout_height=“20dp”
android:gravity=“center_horizontal” />

<LinearLayout
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:orientation=“horizontal”>
</LinearLayout>
<LinearLayout
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:orientation=“horizontal”>
</LinearLayout>
</LinearLayout>


Dengan demikian selesai sudah aplikasi yang kita buat dengan menambahkan fitur login dan register dengan menggunakan php mysql dan sqlite. Sebelum menjalankan aplikasi ini ada beberapa hal yang harus diperhatikan terlebih dahulu Antara lain :
  1. Ubahlah pengaturan pada androidmanifest.xml dengan mengatur class yang akan dijalankan pertama kali dan mengatur hak akses untuk melakukan koneksi ke internet. Berikut ini source codenya.
<?xml version=“1.0” encoding=“utf-8”?>
<manifest xmlns:android=“http://schemas.android.com/apk/res/android”
package=“app.agung.smartshopper”
android:versionCode=“1”
android:versionName=“1.0” >

<uses-sdk
android:minSdkVersion=“14”
android:targetSdkVersion=“14” />
<uses-permission android:name=“android.permission.INTERNET”/>

<application
android:allowBackup=“true”
android:icon=“@drawable/ic_launcher”
android:label=“@string/app_name”
android:theme=“@style/AppTheme” >
<activity
android:name=“.Login”
android:label=“@string/app_name” >
<intent-filter>
<action android:name=“android.intent.action.MAIN” />
<category android:name=“android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
<activity
android:name=“.MainActivity”
android:label=“@string/app_name”  >
</activity>
<activity
android:name=“.Register”
android:label=“@string/app_name”  >
</activity>
</application>

</manifest>

  1. Pastikan bahwa penempatan masing-masing class pada posisi yang sama seperti dibawah ini 2
  2. Selalu Cek alamat ip server dimana database disimpan pada class login dan register karena setiap saat akan ada perubahan ip. 3Demikian artikel singkat mengenai penggunaan fitur login dan register menggunakan php mysql dan sqlite pada aplikasi android. Berikut screenshot hasil tampilan program. Semoga bermanfaat.
Tampilan Awal Sebelum login
4 

Komentar

Postingan populer dari blog ini

Aplikasi kamus bahasa isyarat indonesia 1

Aplikasi kamus bahasa isyarat indonesia 2

Aplikasi kamus bahasa isyarat indonesia 3