Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
1
Register dan Login Android Menggunakan Async Task k...
Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
2
Register dan Login Android Menggunakan Async Task
K...
Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
3
$telepon=$_POST['telepon'];
$nama=$_POST['nama'];
i...
Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
4
$h['nama'] = $data['nama'] ;
$h['alamat'] = $data['...
Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
5
1. activity_dashboard.xml
<LinearLayout xmlns:andro...
Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
6
<Button
android:id="@+id/pasang"
android:layout_wid...
Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
7
2. akunku.xml
<?xml version="1.0" encoding="utf-8"?...
Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
8
android:text="AKUN"
android:textAppearance="?androi...
Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
9
android:paddingLeft="10dp"
android:text="Registrati...
Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
10
android:id="@+id/address"
android:layout_marginTop...
Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
11
<?xml version="1.0" encoding="utf-8"?>
<LinearLayo...
Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
12
<TextView
android:layout_height="wrap_content"
and...
Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
13
File java terdiri atas 8 file java seperti terliha...
Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
14
}
return false;
}
}
b. Akunku.java
/**
* author : ...
Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
15
@Override
protected void onCreate(Bundle savedInst...
Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
16
c. AlertDialogManager.java
package com.login;
impo...
Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
17
d. Dashboard.java
/**
* author : Yusuf Mufti
* ema...
Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
18
//memberi event klik
exit.setOnClickListener(this)...
Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
19
// TODO Auto-generated method stub
finish();
}
});...
Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
20
e. JSONParser.java
package com.login;
import java....
Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
21
HttpResponse httpResponse = httpClient.execute(htt...
Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
22
// Making HTTP request
try {
// check for request ...
Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
23
BufferedReader reader = new BufferedReader(new
Inp...
Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
24
f. Login.java
/**
* author : Yusuf Mufti
* email :...
Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
25
@Override
protected void onCreate(Bundle savedInst...
Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
26
default:
break;
}
}
public class AmbilData extends...
Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
27
JSONObject c = hasil.getJSONObject(i);
// Storing ...
Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
28
}
@Override
public void onBackPressed() {
// TODO ...
Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
29
g. Register.java
/**
* author : Yusuf Mufti
* emai...
Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
30
telepon =(EditText)findViewById(R.id.telepon);
nam...
Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
31
params.add(new
BasicNameValuePair("email", stremai...
Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
32
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startA...
Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
33
public SessionManager(Context context){
this._cont...
Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
34
user.put(KEY_NAME, pref.getString(KEY_NAME, null))...
Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
35
<item name="android:layout_width">wrap_content</it...
Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer
36
5. Androidmanifest.xml editlah menjadi seperti ber...
Upcoming SlideShare
Loading in...5
×

Register dan Login Android Menggunakan AsyncTask ke Database Server

15,054

Published on

Cara untuk membuat halaman daftar dan login dengan aplikasi Android dengan koneksi database server MySQL

Untuk download source codenya dapat buka link https://goo.gl/KQvrP5

Published in: Education, Technology
1 Comment
4 Likes
Statistics
Notes
No Downloads
Views
Total Views
15,054
On Slideshare
0
From Embeds
0
Number of Embeds
4
Actions
Shares
0
Downloads
1,186
Comments
1
Likes
4
Embeds 0
No embeds

No notes for slide

Register dan Login Android Menggunakan AsyncTask ke Database Server

  1. 1. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 1 Register dan Login Android Menggunakan Async Task ke Database Server DAPATKAN SEGERA Buku Panduan Mudah Pengembangan Google Map Android (integrasi dengan MySQL dan SQLite) + CD Source code Penerbit : Andi Offset Terbit : April 2015 Telah tersedia di Gramedia, Togamas, Social Agency dan beberapa toko buku online.
  2. 2. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 2 Register dan Login Android Menggunakan Async Task Ke Database Server Oleh Yusuf Mufti – ym1315@gmail.com- yusufmufti.com Membuat Register / Pendaftaran dan Login pada Android pada tulisan masih memiliki kekurangan seperti belum ada pengecekan apakah email telah terdaftar, komunikasi data login masih menggunakan method GET, dan belum menggunakan library seperti volley. Langkah-langkah yang akan dibahas pada tulisan ini yaitu 1. Membuat database 2. Membuat PHP untuk handle request 3. Membuat projek Android A. Membuat Database. Buatlah database dengan nama “login” dan buatlah tabel “user”. Adapun struktur tabel user sebagai berikut ini. B. PHP untuk handle request Ada 3 file PHP yang kita akan buat, yaitu koneksi.php,register.php dan login.php dan simpan di htdocs dengan folder “login”. - File koneksi.php <?php mysql_connect("localhost","root",""); mysql_select_db("login"); ?> - File register.php <?php $email = $_POST['email']; $password=$_POST['password']; $alamat=$_POST['alamat'];
  3. 3. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 3 $telepon=$_POST['telepon']; $nama=$_POST['nama']; include "koneksi.php"; $namaTabel = "user"; header('Content-Type: text/xml'); $query = "INSERT INTO $namaTabel VALUES('','$nama','$email','$password','$alamat','$telepon')"; $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"; $username = $_GET["username"]; $password = $_GET["password"]; $query = "select * from user where email='$username' 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'] ;
  4. 4. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 4 $h['nama'] = $data['nama'] ; $h['alamat'] = $data['alamat'] ; $h['email'] = $data['email']; 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); } ?> C. Membuat Projek Android - Membuat projek Android dengan klik File > New > Android Application Project, kemudian konfigurasi untuk penamaan package, icon, dan file xml. - Membuat file xml di folder res layout Sebelum membahas kodenya, saya ingin menunjukkan struktur file di folder res sebagai berikut
  5. 5. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 5 1. activity_dashboard.xml <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=".Dashboard" > <ScrollView android:layout_height="match_parent" android:layout_width="match_parent" android:scrollbarStyle="insideInset"> <LinearLayout android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20sp">
  6. 6. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 6 <Button android:id="@+id/pasang" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" style="@style/DashboardButton" android:drawableTop="@drawable/tomboladd" android:text="Akun" android:textColor="#000000"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20sp"> <Button android:id="@+id/exit" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" style="@style/DashboardButton" android:drawableTop="@drawable/tombolexit" android:text="Keluar" android:textColor="#000000"/> </LinearLayout> </LinearLayout> </ScrollView> </LinearLayout> YUSUF MUFTI Freelance Programmer www.yusufmufti.com Email : ym1315@gmail.com SMS - WA : +62 896 373 191 80 FB : yusufmufti
  7. 7. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 7 2. akunku.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:orientation="vertical" > <TextView android:id="@+id/status" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Status" android:layout_marginLeft="10dp" android:textColor="#aa0000" /> <Button android:id="@+id/logout" android:layout_width="wrap_content" android:gravity="right" android:layout_gravity="right" android:layout_height="wrap_content" android:text="Logout" android:textColor="#aa0000" /> <TextView android:id="@+id/textView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:gravity="center_horizontal"
  8. 8. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 8 android:text="AKUN" android:textAppearance="?android:attr/textAppearanceLarge" /> </LinearLayout> 3. 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:orientation="vertical" > <ScrollView android:layout_height="match_parent" android:layout_width="match_parent" android:scrollbarStyle="insideInset"> <LinearLayout android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical"> <TextView android:layout_marginTop="10dp" android:layout_height="wrap_content" android:layout_width="match_parent"
  9. 9. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 9 android:paddingLeft="10dp" android:text="Registration" android:textSize="25sp" android:textColor="#aabb00" android:gravity="center_horizontal"/> <EditText android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/email" android:layout_marginTop="10dp" android:layout_marginLeft="10dp" android:paddingRight="10dp" android:hint="insert email"/> <EditText android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/password" android:layout_marginTop="10dp" android:layout_marginLeft="10dp" android:paddingRight="10dp" android:hint="insert password" android:inputType="textPassword"/> <EditText android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/nama" android:layout_marginTop="10dp" android:layout_marginLeft="10dp" android:paddingRight="10dp" android:hint="insert your name"/> <EditText android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/telepon" android:layout_marginTop="10dp" android:layout_marginLeft="10dp" android:paddingRight="10dp" android:hint="insert your number phone" android:inputType="phone"/> <EditText android:layout_height="wrap_content" android:layout_width="match_parent"
  10. 10. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 10 android:id="@+id/address" android:layout_marginTop="10dp" android:layout_marginLeft="10dp" android:paddingRight="10dp" android:hint="insert your address" android:minLines="3"/> <Button android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/submit" android:layout_marginTop="10dp" android:layout_marginLeft="10dp" android:paddingRight="10dp" android:text="Register" /> <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Isilah semua inputan" android:id="@+id/keterangan" android:layout_marginLeft="13dp" android:textColor="#aa0000"/> </LinearLayout> </ScrollView> </LinearLayout> 4. login.xml
  11. 11. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 11 <?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:orientation="vertical" > <ScrollView android:layout_height="match_parent" android:layout_width="match_parent" android:scrollbarStyle="insideInset"> <LinearLayout android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical"> <TextView android:layout_marginTop="10dp" android:layout_height="wrap_content" android:layout_width="match_parent" android:paddingLeft="10dp" android:text="Login" android:textSize="25sp" android:textColor="#aabb00" android:gravity="center_horizontal"/> <EditText android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/username" android:layout_marginTop="10dp" android:layout_marginLeft="10dp" android:paddingRight="10dp" android:hint="insert username"/> <EditText android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/password" android:layout_marginTop="10dp" android:layout_marginLeft="10dp" android:paddingRight="10dp" android:hint="insert password" android:inputType="textPassword"/> <Button android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/submit" android:layout_marginTop="10dp" android:layout_marginLeft="10dp" android:paddingRight="10dp" android:text="Login" />
  12. 12. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 12 <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Masukkan username dan password" android:id="@+id/keterangan" android:layout_marginLeft="13dp" android:textColor="#aa0000"/> <Button android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/register" android:layout_marginTop="50dp" android:layout_marginLeft="10dp" android:paddingRight="10dp" android:text="Register" /> </LinearLayout> </ScrollView> </LinearLayout>
  13. 13. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 13 File java terdiri atas 8 file java seperti terlihat pada gambar berikut. a. ConnectionDetector.java package com.cekinternet; /* * Class untuk pengecekan internet */ import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; public class ConnectionDetector { private Context _context; public ConnectionDetector(Context context) { this._context = context; } public boolean isConnectingToInternet() { ConnectivityManager connectivity = (ConnectivityManager) _context .getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity != null) { NetworkInfo[] info = connectivity.getAllNetworkInfo(); if (info != null) for (int i = 0; i < info.length; i++) if (info[i].getState() == NetworkInfo.State.CONNECTED) { return true; }
  14. 14. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 14 } return false; } } b. Akunku.java /** * author : Yusuf Mufti * email : ym1315@gmail.com * web : yusufmufti.com */ package com.login; import java.util.HashMap; import org.json.JSONArray; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.text.Html; import android.view.View; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.yusfa.login.R; public class Akunku extends Activity{ //inisiasi variabel yang akan digunakan Button logout; SessionManager session; ListView lv; ProgressDialog pDialog; JSONArray contacts = null; String email, name;
  15. 15. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 15 @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.akunku); //membuat session untuk user session = new SessionManager(getApplicationContext()); Toast.makeText(getApplicationContext(), "User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG).show(); session.checkLogin(); HashMap<String, String> user = session.getUserDetails(); name = user.get(SessionManager.KEY_NAME); email=user.get(SessionManager.KEY_EMAIL); TextView status = (TextView)findViewById(R.id.status); status.setText(Html.fromHtml("Welcome,<b>"+name+"</b> ")); //inisiasi tombol Logout dan memberi fungsi klik logout = (Button)findViewById(R.id.logout); logout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub session.logoutUser(); finish(); } }); } @Override public void onBackPressed() { // TODO Auto-generated method stub Intent i = new Intent(getApplicationContext(), Dashboard.class); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(i); finish(); } }
  16. 16. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 16 c. AlertDialogManager.java package com.login; import com.yusfa.login.R; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; public class AlertDialogManager { /** * androidhive * */ @SuppressWarnings("deprecation") public void showAlertDialog(Context context, String title, String message, Boolean status) { AlertDialog alertDialog = new AlertDialog.Builder(context).create(); // Setting Dialog Title alertDialog.setTitle(title); // Setting Dialog Message alertDialog.setMessage(message); if(status != null) // Setting alert dialog icon alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail); // Setting OK Button alertDialog.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); // Showing Alert Message alertDialog.show(); } }
  17. 17. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 17 d. Dashboard.java /** * author : Yusuf Mufti * email : ym1315@gmail.com * web : yusufmufti.com */ package com.login; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; import com.cekinternet.ConnectionDetector; import com.yusfa.login.R; public class Dashboard extends Activity implements OnClickListener { Button exit, pasang; Intent a; ConnectionDetector cd; Boolean isInternetPresent = false; AlertDialogManager alert = new AlertDialogManager(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dashboard); //Inisiasi exit=(Button)findViewById(R.id.exit); pasang =(Button)findViewById(R.id.pasang); cekInternet();
  18. 18. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 18 //memberi event klik exit.setOnClickListener(this); } //menghandle klik @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.pasang: a = new Intent(getApplicationContext(), Akunku.class); startActivity(a); break; case R.id.exit: Dialog(); break; default: break; } } //dialog untuk keluar public void Dialog(){ AlertDialog.Builder builder= new AlertDialog.Builder(this); builder.setMessage("Keluar dari Aplikasi ?"); builder.setPositiveButton("Batal", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int arg1) { // TODO Auto-generated method stub dialog.dismiss(); } }); builder.setNegativeButton("Ya", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) {
  19. 19. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 19 // TODO Auto-generated method stub finish(); } }); builder.create().show(); } //menghandle tombol back smartphone @Override public void onBackPressed() { // TODO Auto-generated method stub Dialog(); } public void cekInternet(){ //memanggil pengecekan internet cd = new ConnectionDetector(getApplicationContext()); isInternetPresent = cd.isConnectingToInternet(); if (isInternetPresent) { Toast.makeText(getApplicationContext(), "Anda Memiliki Koneksi Internet", Toast.LENGTH_SHORT) .show(); pasang.setOnClickListener(this); } else { alert.showAlertDialog(Dashboard.this, "Peringatan", "Internet tidak tersedia, Anda harus mengecek koneksi internet.", false); } } }
  20. 20. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 20 e. JSONParser.java package com.login; 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);
  21. 21. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 21 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) {
  22. 22. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 22 // 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 {
  23. 23. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 23 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; } }
  24. 24. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 24 f. Login.java /** * author : Yusuf Mufti * email : ym1315@gmail.com * web : yusufmufti.com */ package com.login; import java.util.ArrayList; import java.util.HashMap; import org.json.JSONArray; import org.json.JSONObject; import com.cekinternet.ConnectionDetector; import com.yusfa.login.R; 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.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class Login extends Activity implements OnClickListener{ Button register, login; Intent a; EditText username, password; String url, success; SessionManager session; AlertDialogManager alert = new AlertDialogManager(); ConnectionDetector cd; Boolean isInternetPresent = false;
  25. 25. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 25 @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.login); session = new SessionManager(getApplicationContext()); Toast.makeText(getApplicationContext(), "User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG).show(); register = (Button)findViewById(R.id.register); login = (Button)findViewById(R.id.submit); username = (EditText)findViewById(R.id.username); password = (EditText)findViewById(R.id.password); cekInternet(); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.register: a = new Intent (Login.this, Register.class); startActivity(a); break; case R.id.submit: url = "http://10.0.2.2:8080/login/login.php?" + "username=" +username.getText().toString()+"&password=" + password.getText().toString(); if(username.getText().toString().trim().length()>0 &&password.getText().toString().trim().length()>0){ new AmbilData().execute(); }else{ alert.showAlertDialog(Login.this, "Login failed..", "Silakan isi username adan password", false); } break;
  26. 26. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 26 default: break; } } public class AmbilData 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("Loading Data ..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } @Override protected String doInBackground(String... arg0) { // TODO Auto-generated method stub 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++) {
  27. 27. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 27 JSONObject c = hasil.getJSONObject(i); // Storing each json item in variable 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, Akunku.class); startActivity(a); finish(); } else{ TextView keterangan = (TextView)findViewById(R.id.keterangan); keterangan.setText("Maaf username atau password Anda Salah"); alert.showAlertDialog(Login.this, "Login failed..", "Username/Password is incorrect", false); } }
  28. 28. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 28 } @Override public void onBackPressed() { // TODO Auto-generated method stub Intent i = new Intent(getApplicationContext(), Dashboard.class); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(i); finish(); } //cek internet public void cekInternet(){ //memanggil pengecekan internet cd = new ConnectionDetector(getApplicationContext()); isInternetPresent = cd.isConnectingToInternet(); // check for Internet status if (isInternetPresent) { Toast.makeText(getApplicationContext(), "Anda Memiliki Koneksi Internet", Toast.LENGTH_SHORT) .show(); register.setOnClickListener(this); login.setOnClickListener(this); } else { alert.showAlertDialog(Login.this, "Peringatan", "Internet tidak tersedia, Anda harus mengecek koneksi internet.", false); } } }
  29. 29. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 29 g. Register.java /** * author : Yusuf Mufti * email : ym1315@gmail.com * web : yusufmufti.com */ package com.login; import java.util.ArrayList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONObject; import com.yusfa.login.R; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; 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, alamat, telepon, nama; private static String url = "http://10.0.2.2:8080/login/register.php"; Button submit; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.register); email =(EditText)findViewById(R.id.email); password=(EditText)findViewById(R.id.password); alamat=(EditText)findViewById(R.id.address);
  30. 30. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 30 telepon =(EditText)findViewById(R.id.telepon); nama =(EditText)findViewById(R.id.nama); submit = (Button)findViewById(R.id.submit); submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub new InputData().execute(); } }); } public class InputData 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... args) { String strnama = nama.getText().toString(); String stralamat = alamat.getText().toString(); String stremail = email.getText().toString(); String strpassword = password.getText().toString(); String strtelepon = telepon.getText().toString(); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("nama", strnama)); params.add(new BasicNameValuePair("alamat", stralamat));
  31. 31. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 31 params.add(new BasicNameValuePair("email", stremail)); params.add(new BasicNameValuePair("password", strpassword)); params.add(new BasicNameValuePair("telepon", strtelepon)); JSONObject json = jsonParser.makeHttpRequest(url, "POST", params); 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(); } else { Toast.makeText(getApplicationContext(), "Registrasi gagal", Toast.LENGTH_LONG).show(); } } } @Override public void onBackPressed() { // TODO Auto-generated method stub Intent i = new Intent(getApplicationContext(), Dashboard.class);
  32. 32. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 32 i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(i); finish(); } } h. SessionManager.java package com.login; /** * source code androidhive */ 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 = "name"; public static final String KEY_EMAIL = "email"; // Constructor
  33. 33. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 33 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, Login.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>();
  34. 34. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 34 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, Login.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); } } Sedikit tambahan, 1. Untuk file dimens.xml di dalam folder res /value pastikan terdapat kode berikut ini <resources> <!-- Default screen margins, per the Android Design guidelines. --> <dimen name="activity_horizontal_margin">16dp</dimen> <dimen name="activity_vertical_margin">16dp</dimen> </resources> 2. Kemudian untuk styles.xml di dalam folder res/value pastikan terdapat kode berikut ini, jika tidak ada ketikalah di dalam <resource></resource> <style name="DashboardButton"> <item name="android:layout_gravity">center_vertical</item>
  35. 35. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 35 <item name="android:layout_width">wrap_content</item> <item name="android:layout_height">wrap_content</item> <item name="android:gravity">center_horizontal</item> <item name="android:drawablePadding">2dp</item> <item name="android:textSize">16dp</item> <item name="android:textStyle">bold</item> <item name="android:textColor">#ffffff</item> <item name="android:background">@null</item> </style> 3. Kode tomboladd.xml di dalam folder res/drawable-hdpi <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/add_100_pressed" android:state_focused="true" android:state_pressed="true" /> <item android:drawable="@drawable/add_100_pressed" android:state_focused="false" android:state_pressed="true" /> <item android:drawable="@drawable/add_100_pressed" android:state_focused="true" /> <item android:drawable="@drawable/add_100" android:state_focused="false" android:state_pressed="false" /> </selector> 4. Kode tombolexit.xml di dalam folder res/drawable-hdpi <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/exit_pressed" android:state_focused="true" android:state_pressed="true" /> <item android:drawable="@drawable/exit_pressed" android:state_focused="false" android:state_pressed="true" /> <item android:drawable="@drawable/exit_pressed" android:state_focused="true" /> <item android:drawable="@drawable/exit" android:state_focused="false" android:state_pressed="false" /> </selector>
  36. 36. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 36 5. Androidmanifest.xml editlah menjadi seperti berikut ini <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.yusfa.login" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <!-- Network State Permissions to check available or not--> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <application android:allowBackup="true" android:icon="@drawable/icon" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.login.Dashboard" 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="com.login.Login"></activity> <activity android:name="com.login.Register"></activity> <activity android:name="com.login.Akunku"></activity> </application> </manifest> Anda telah selesai membuat projek Register dan Login. Klik kanan projek dan pilih Run As – Android Application Project. SOURCE CODE dapat diunduh di SINI

×