Tutorial Android dan MySQL dengan PHP

Sunday, January 17, 2016
1. Pastikan telah menginstal ADT Bundle/Android Studio dan Xampp
2. Mengakses PhpMyAdmin di browser -> localhost/xampp/phpmyadmin
3. Buat Database di PhpMyAdmin dengan nama -> "android"
4. Buat Tabel di database android dengan nama -> "pengguna", buat kolom username, dan password
5. Buat folder baru di C:/xampp/htdocs/ dengan nama -> Android
6. Ketiikan kode PHP dibawah ini untuk menyimpan data, bisa menggunakan editor notepad dan simpan dengan nama save.php

<?php
$conn = mysql_connect("localhost","root",""); 
mysql_select_db("android");
 
$username=$_POST['username'];
$password=$_POST['password'];
 
$query="insert into pengguna values('$username','$password')";
$result=mysql_query($query);
?>

7. Buat project baru di eclipse dengan nama AndroidMySQL
8. Buat tampilan berikut :

9. Buat kelas ConnectHttpClient.java
package com.wim.androidmysql2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
 
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
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.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

public class ConnectHttpClient {
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
    
    public static HttpClient mHttpClient;
    
    //return an HttpClient object with connection parameters set
    private static HttpClient getHttpClient() {
        if (mHttpClient == null) {
            mHttpClient = new DefaultHttpClient();
            final HttpParams params = mHttpClient.getParams();
            HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
            HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
            ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
        }
        return mHttpClient;
    }
    
    public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
            HttpPost request = new HttpPost(url);
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
            request.setEntity(formEntity);
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static String executeHttpGet(String url) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(url));
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
}

10. Tambahkan kode berikut di MainActivity.java
package com.wim.androidmysql2;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

 TextView error;
 EditText txusername, txpassword;
 Button simpan;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  txusername = (EditText) findViewById(R.id.editText1);
  txpassword = (EditText) findViewById(R.id.editText2);
  error = (TextView) findViewById(R.id.textView3);
  simpan = (Button) findViewById(R.id.button1);
  
  simpan.setOnClickListener(new View.OnClickListener() {
   
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    
    ArrayList<NameValuePair> postParameter = new ArrayList<NameValuePair>();
    postParameter.add((new BasicNameValuePair("username", txusername.getText().toString())));
    postParameter.add((new BasicNameValuePair("password", txpassword.getText().toString())));
    
    String response = null;
    
    try{
     response = ConnectHttpClient.executeHttpPost("http://10.0.2.2/Android/save.php", postParameter);
     
     String res = response.toString();
              res = res.trim();
              res = res.replaceAll("\\s+","");
                 
              if (res.equals("1")){
               error.setText("Gagal");
              }else{
               error.setText("Sukses");
              }
    }catch(Exception e){
     e.printStackTrace();
    }
   }
  });
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

}

11. Tambahkan permission di AndroidManifest.xml


    

    
        
            
                

                
            
        
    
 


12. Selesai, tinggal di run

Semoga bermanfaat
Happy Coding :)

Share this :

Previous
Next Post »
0 Komentar

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