Your SlideShare is downloading. ×
Register dan Login Android Menggunakan Database
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Register dan Login Android Menggunakan Database

12,575

Published on

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

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

kode 10.0.2.2:8080 silakan diganti 10.0.2.2

Published in: Education, Technology
0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
12,575
On Slideshare
0
From Embeds
0
Number of Embeds
4
Actions
Shares
0
Downloads
749
Comments
0
Likes
3
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 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 akan dibahas berikut ini, Langkah-langkahnya 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']; $telepon=$_POST['telepon']; $nama=$_POST['nama'];
  • 2. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 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'] ; $h['nama'] = $data['nama'] ; $h['alamat'] = $data['alamat'] ; $h['email'] = $data['email'];
  • 3. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 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
  • 4. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 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">
  • 5. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer <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 ANDROID Email BLACKBERRY OS 10 IPHONE PHP MYSQL : ym1315@gmail.com JUALAN BAJU KOKO harga HEBOH HP : +62 896 373 191 80 http://goo.gl/KZpqaR WA : +62 81 915 10 9090 FB : yusufmufti Twitter : @yusuf_mufti Freelance Programmer www.yusufmufti.com
  • 6. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 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"
  • 7. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 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"
  • 8. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 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"
  • 9. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 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
  • 10. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer <?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" />
  • 11. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer <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> YUSUF MUFTI ANDROID Email BLACKBERRY OS 10 IPHONE PHP MYSQL : ym1315@gmail.com JUALAN BAJU KOKO harga HEBOH HP : +62 896 373 191 80 http://goo.gl/KZpqaR WA : +62 81 915 10 9090 FB : yusufmufti Twitter : @yusuf_mufti Freelance Programmer www.yusufmufti.com
  • 12. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 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; }
  • 13. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer } 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;
  • 14. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer @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(); } }
  • 15. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 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(); } } d. Dashboard.java /** * author : Yusuf Mufti
  • 16. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer * email * web */ : ym1315@gmail.com : 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(); //memberi event klik exit.setOnClickListener(this);
  • 17. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer } //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) { // TODO Auto-generated method stub
  • 18. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 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); } } } 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;
  • 19. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 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();
  • 20. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer } 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
  • 21. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 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"); }
  • 22. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 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; } } f. Login.java /** * author * email * web */ : Yusuf Mufti : ym1315@gmail.com : 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;
  • 23. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 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; @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 login username password = (Button)findViewById(R.id.register); = (Button)findViewById(R.id.submit); = (EditText)findViewById(R.id.username); = (EditText)findViewById(R.id.password); cekInternet(); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) {
  • 24. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 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; 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(); }
  • 25. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer @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++) { 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; }
  • 26. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer @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); } } } @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(),
  • 27. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer "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); } } } 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;
  • 28. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 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); 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(); }
  • 29. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer @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)); 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();
  • 30. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 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); 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;
  • 31. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer // 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 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()){
  • 32. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 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>(); 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); } }
  • 33. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 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> <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>
  • 34. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer 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> 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" />
  • 35. Yusuf Mufti – ym1315@gmail.com – 089637319180 – freelance programmer <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. YUSUF MUFTI ANDROID Email BLACKBERRY OS 10 IPHONE PHP MYSQL : ym1315@gmail.com JUALAN BAJU KOKO harga HEBOH HP : +62 896 373 191 80 http://goo.gl/KZpqaR WA : +62 81 915 10 9090 FB : yusufmufti Freelance Programmer www.yusufmufti.com

×