(C.S SeAPOTIK part1)
CLIENT SERVER APLIKASI SeAPOTIK (Part1)
Laporan ini membahas cara mengkoneksikan aplikasi android dengan database, untuk itu kita memerlukan :
- Database
- File php
- File koneksi android ke file php
- Langsung saja, disini saya menyiapkan database dengan nama seapotik dan membuat table user seperti berikut :
- kemudian kita buat folder di htdocs dengan nama seapotik, dan buat 3 buahfile php dengan nama masing-masing : koneksi.php, register.php dan login.php
- kemudian isi
- File koneksi.php :
<?php
mysql_connect("localhost","root","");
mysql_select_db("seapotik");
?>
- File register.php :
<?php
$nama=$_POST['nama'];
$email = $_POST['email'];
$password=$_POST['password'];
$alamat=$_POST['alamat'];
$telpon=$_POST['telpon'];
include "koneksi.php";
$query = "INSERT INTO user (nama,email,password,alamat,telpon)VALUES('$nama','$email','$password','$alamat','$telpon')";
$hasil = mysql_query($query);
if($hasil)
{
$response["success"] = "1";
$response["message"] = "Data sukses diinput";
echo json_encode($response);
}
else
{$response["success"] = "0";
$response["message"] = "Maaf , terjadi kesalahan";
// echoing JSON response
echo json_encode($response);
}
?>
- File login.php :
<?php
include "koneksi.php";
$email = $_GET["email"];
$password = $_GET["password"];
$query = "select * from user where email='$email' and password='$password' ";
$hasil = mysql_query($query);
if (mysql_num_rows($hasil) > 0) {
$response = array();
$response["login"] = array();
while ($data = mysql_fetch_array($hasil))
{
$h['id'] = $data['id'] ;
$h['nama'] = $data['nama'] ;
$h['email'] = $data['email'] ;
$h['password'] = $data['password'];
$h['alamat'] = $data['alamat'];
$h['telpon'] = $data['telpon'];
array_push($response["login"], $h);
}
$response["success"] = "1";
echo json_encode($response);
}
else {
$response["success"] = "0";
$response["message"] = "Tidak ada data";
echo json_encode($response);
}
?>
- Selanjutnya kita buka ADT dan membuat sebuah project baru, dengan nama MainActivity.java dan activity_main.xml
- Isi file activity_main.xml dengan script berikut :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="@drawable/back1"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:id="@+id/tentang"
android:layout_width="fill_parent"
android:textStyle="bold"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Tentang" />
<Button
android:id="@+id/masuk"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/member"
android:layout_alignParentLeft="true"
android:text="MASUK"
android:textStyle="bold" />
<Button
android:id="@+id/member"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/seapotik"
android:layout_alignParentLeft="true"
android:text="Member/Pelanggan"
android:textStyle="bold" />
<Button
android:id="@+id/seapotik"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/tentang"
android:layout_alignParentLeft="true"
android:text="SeAPOTIK"
android:textStyle="bold" />
</RelativeLayout>
- Dan file MainActivity.java isi dengan script sebagai berikut :
package jhohannes.purba;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
Button a,b,c,d;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
a = (Button)findViewById(R.id.masuk);
a.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Login.class);
startActivity(intent);
}
});
b = (Button)findViewById(R.id.member);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Member.class);
startActivity(intent);
}
});
c = (Button)findViewById(R.id.seapotik);
c.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Seapotik.class);
startActivity(intent);
}
});
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
- Kita buat 2 file untuk mengkoneksikan android dengan database, kita buat file dengan nama JSONParser.java dan SessionManager.java
- Isi file JSONParser.java dengan script berikut :
package jhohannes.purba;
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() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
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;
}
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;
}
}
- Dan file SessionManager.java isi dengan script berikut :
package jhohannes.purba;
import java.util.HashMap;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
@SuppressLint("CommitPrefEdits")
public class SessionManager {
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// nama sharepreference
private static final String PREF_NAME = "Sesi";
// All Shared Preferences Keys
private static final String IS_LOGIN = "IsLoggedIn";
public static final String KEY_NAME = "nama";
public static final String KEY_EMAIL = "email";
// Constructor
public SessionManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
/**
* Create login session
* */
public void createLoginSession(String name, String email){
// Storing login value as TRUE
editor.putBoolean(IS_LOGIN, true);
editor.putString(KEY_NAME, name);
editor.putString(KEY_EMAIL, email);
editor.commit();
}
/**
* Check login method wil check user login status
* If false it will redirect user to login page
* Else won't do anything
* */
public void checkLogin(){
// Check login status
if(!this.isLoggedIn()){
Intent i = new Intent(_context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
_context.startActivity(i);
//((Activity)_context).finish();
}
}
/**
* Get stored session data
* */
public HashMap<String, String> getUserDetails(){
HashMap<String, String> user = new HashMap<String, String>();
user.put(KEY_NAME, pref.getString(KEY_NAME, null));
user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
return user;
}
/**
* Clear session details
* */
public void logoutUser(){
// Clearing all data from Shared Preferences
editor.clear();
editor.commit();
Intent i = new Intent(_context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
_context.startActivity(i);
}
public boolean isLoggedIn(){
return pref.getBoolean(IS_LOGIN, false);
}
}
- Kemudian kita buat dua buah Activity dengan nama Login.java (activity_login.xml) dan Register.java (activity_register.xml)
- Login.java :
package jhohannes.purba;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.View;import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Login extends Activity {
Button daftar, login;
Intent a;
EditText email, password;
String url, success;
SessionManager session;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
session = new SessionManager(getApplicationContext());
Toast.makeText(getApplicationContext(),
"User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG)
.show();
daftar = (Button) findViewById(R.id.daftar);
login = (Button) findViewById(R.id.login);
email = (EditText) findViewById(R.id.email);
password = (EditText) findViewById(R.id.password);
daftar.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View arg0) {
Intent daftar = new Intent(Login.this, Register.class);
startActivity(daftar);
}
});
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
url = "http://10.0.2.2/seapotik/login.php?" + "email="
+ email.getText().toString() + "&password="
+ password.getText().toString();
if (email.getText().toString().trim().length() > 0
&& password.getText().toString().trim().length() > 0)
{
new Masuk().execute();
}
else
{
Toast.makeText(getApplicationContext(), "Username/password masih kosong gan.!!", Toast.LENGTH_LONG).show();
}
}
});
}
public class Masuk extends AsyncTask<String, String, String>
{
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
ProgressDialog pDialog;
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Tunggu Bentar ya...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... arg0) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
try {
success = json.getString("success");
Log.e("error", "nilai sukses=" + success);
JSONArray hasil = json.getJSONArray("login");
if (success.equals("1")) {
for (int i = 0; i < hasil.length(); i++) {
JSONObject c = hasil.getJSONObject(i);
String nama = c.getString("nama").trim();
String email = c.getString("email").trim();
session.createLoginSession(nama, email);
Log.e("ok", " ambil data");
}
} else {
Log.e("erro", "tidak bisa ambil data 0");
}
} catch (Exception e) {
// TODO: handle exception
Log.e("erro", "tidak bisa ambil data 1");
}
return null;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pDialog.dismiss();
if (success.equals("1")) {
a = new Intent(Login.this, MainObat.class);
startActivity(a);
finish();
} else {
Toast.makeText(getApplicationContext(), "Username/password salah gan.!!", Toast.LENGTH_LONG).show();
}
}
}
}
- activity_login.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/back2"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#ffff"
android:text="Silahkan Login"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbarStyle="insideInset" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:hint="email"
android:paddingRight="10dp" />
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:hint="password"
android:inputType="textPassword"
android:paddingRight="10dp" />
<Button
android:id="@+id/login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:paddingRight="10dp"
android:text="Login" />
<TextView
android:id="@+id/textView2"
android:gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#ffff"
android:text="Belum Punya Akun ? Silahkan Daftar"
android:textAppearance="?android:attr/textAppearanceSmall"/>
<Button
android:id="@+id/daftar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="50dp"
android:paddingRight="10dp"
android:text="Daftar" />
</LinearLayout>
</ScrollView>
</LinearLayout>
- Register.java :
package jhohannes.purba;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Register extends Activity {
ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText email, password, nama, alamat, telpon;
Button daftar;
private static String url = "http://10.0.2.2/seapotik/Register.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
email = (EditText) findViewById(R.id.email);
password = (EditText) findViewById(R.id.password);
nama = (EditText) findViewById(R.id.nama);
alamat = (EditText) findViewById(R.id.alamat);
telpon = (EditText) findViewById(R.id.telpon);
daftar = (Button) findViewById(R.id.daftar);
final EmailValidator emailValid = new EmailValidator();
daftar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!emailValid.validate(email.getText().toString())) {
Toast.makeText(Register.this, "Emailnya ga valid",
Toast.LENGTH_LONG).show();
email.setText("");
} else {
new daftarAku().execute();
}
}
});
}
public class daftarAku extends AsyncTask<String, String, String> {
String success;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Register.this);
pDialog.setMessage("Proses mendaftar...");
pDialog.setIndeterminate(false);
pDialog.show();
}
@Override
protected String doInBackground(String... params) {
String strnama = nama.getText().toString();
String stremail = email.getText().toString();
String strpassword = password.getText().toString();
String stralamat = alamat.getText().toString();
String strtelpon = telpon.getText().toString();
List<NameValuePair> nvp = new ArrayList<NameValuePair>();
nvp.add(new BasicNameValuePair("nama", strnama));
nvp.add(new BasicNameValuePair("email", stremail));
nvp.add(new BasicNameValuePair("password", strpassword));
nvp.add(new BasicNameValuePair("alamat", stralamat));
nvp.add(new BasicNameValuePair("telpon", strtelpon));
JSONObject json = jsonParser.makeHttpRequest(url, "POST", nvp);
try {
success = json.getString("success");
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Error",
Toast.LENGTH_LONG).show();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
if (success.equals("1")) {
Toast.makeText(getApplicationContext(), "Regitrasi sukses",
Toast.LENGTH_LONG).show();
finish();
} else {
Toast.makeText(getApplicationContext(), "Registrasi gagal",
Toast.LENGTH_LONG).show();
}
}
}
public class EmailValidator {
private Pattern pattern;
private Matcher matcher;
private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
public EmailValidator() {
pattern = Pattern.compile(EMAIL_PATTERN);
}
public boolean validate(final String hex) {
matcher = pattern.matcher(hex);
return matcher.matches();
}
}
}
- activity_register.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/back2"
android:orientation="vertical" >
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbarStyle="insideInset" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center_horizontal"
android:paddingLeft="10dp"
android:textColor="#ffff"
android:text="Pendaftaran"
android:textSize="25sp" />
<EditText
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:hint="email"
android:paddingRight="10dp" />
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:hint="password"
android:inputType="textPassword"
android:paddingRight="10dp" />
<EditText
android:id="@+id/nama"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:hint="nama"
android:paddingRight="10dp" />
<EditText
android:id="@+id/alamat"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:hint="alamat"
android:paddingRight="10dp" />
<EditText
android:id="@+id/telpon"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:hint="telpon"
android:paddingRight="10dp" />
<Button
android:id="@+id/daftar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:paddingRight="10dp"
android:text="Daftar" />
<TextView
android:id="@+id/keterangan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="13dp"
android:text="Isilah semua inputan"
android:textColor="#ffff" />
</LinearLayout>
</ScrollView>
</LinearLayout>
- Dan hasil sementara akan terlihat seperti berikut :
- Oke, sampai disini dulu, kita lanjutkan dipart selanjutnya.
No comments