menyimpan data di android dengan database mySQL dan PHP
Langkah petama yang
harus di lakukan adalah meyiapkan database dan tabel di mysql.
nama database : latihan
nama tabel : user1DROP TABLE IF EXISTS `user1`;
CREATE TABLE `user1` (
`nama` varchar(10) NOT NULL,
`alamat` varchar(10) default NULL,
`ttl` varchar(10) default NULL,
`pekerjaan` varchar(10) default NULL,
`gaji` varchar(10) default NULL,
`tunjangan` varchar(10) default NULL,
`thr` varchar(10) default NULL,
PRIMARY KEY (`nama`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
setelah itu buat file PHP yang berfungsi untuk "web service" atau "insert" data ke database.
simpan1.php
<?php
$un=$_POST['nama'];
$pw=$_POST['alamat'];
$rpw=$_POST['ttl'];
$nl=$_POST['pekerjaan'];
$gj=$_POST['gaji'];
$tnj=$_POST['tunjangan'];
$th=$_POST['thr'];
$conn = mysql_connect("localhost","root","root");
mysql_select_db("latihan");
$query = "INSERT INTO user1 (nama,alamat,ttl,pekerjaan,gaji,tunjangan,thr) values ('$un','$pw','$rpw','$nl','$gj','$tnj','$th')";
$result = mysql_query($query) or die("Gagal .");
if (mysql_num_rows($result) == 1)
{
echo 1;
}
else {
// print status message
echo 0;
}
?>
kemudian buat viewnya yaitu activity_main.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical" >
<RelativeLayout
android:id="@+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFF00"
android:gravity="right" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="3dp"
android:text="nama" />
<EditText
android:id="@+id/editText2"
android:layout_width="186dp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="34dp"
android:layout_toRightOf="@+id/textView3"
android:layout_x="114dp"
android:layout_y="-2dp"
android:ems="10"
android:inputType="textPersonName" />
<EditText
android:id="@+id/editText1"
android:layout_width="191dp"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText2"
android:layout_below="@+id/editText2"
android:layout_x="114dp"
android:layout_y="59dp"
android:ems="10"
android:inputType="textPersonName" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/editText2"
android:layout_marginTop="15dp"
android:layout_x="0dp"
android:layout_y="69dp"
android:text="alamat" />
<EditText
android:id="@+id/editText3"
android:layout_width="186dp"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_alignRight="@+id/editText1"
android:layout_below="@+id/editText1"
android:layout_x="119dp"
android:layout_y="123dp"
android:ems="10" >
<requestFocus />
</EditText>
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/editText3"
android:layout_marginLeft="9dp"
android:layout_marginTop="15dp"
android:layout_x="8dp"
android:layout_y="194dp"
android:text="pekerjaan" />
<EditText
android:id="@+id/editText4"
android:layout_width="178dp"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText3"
android:layout_alignRight="@+id/editText1"
android:layout_below="@+id/editText3"
android:layout_x="121dp"
android:layout_y="184dp"
android:ems="10"
android:inputType="textPersonName" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/editText1"
android:layout_marginLeft="3dp"
android:layout_marginTop="20dp"
android:layout_x="2dp"
android:layout_y="136dp"
android:text="tempat tinggal"/>
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView6"
android:layout_alignRight="@+id/textView4"
android:layout_below="@+id/editText4"
android:layout_marginTop="15dp"
android:text="gaji" />
<EditText
android:id="@+id/editText5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText4"
android:layout_below="@+id/editText4"
android:ems="10"
android:inputType="textPersonName" />
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignRight="@+id/editText2"
android:layout_below="@+id/editText5"
android:layout_marginTop="90dp"
android:text="simpan" />
<EditText
android:id="@+id/editText6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText5"
android:layout_alignParentRight="true"
android:layout_below="@+id/editText5"
android:ems="10"
android:inputType="textPersonName" />
<EditText
android:id="@+id/editText7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText6"
android:layout_below="@+id/editText6"
android:ems="10"
android:inputType="textPersonName" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/button1"
android:text="keluar" />
<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText6"
android:layout_alignBottom="@+id/editText6"
android:layout_alignLeft="@+id/textView4"
android:text="Tunjangan" />
<TextView
android:id="@+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText7"
android:layout_alignBottom="@+id/editText7"
android:layout_alignLeft="@+id/textView6"
android:layout_alignRight="@+id/textView3"
android:text="THR" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/button2"
android:src="@drawable/andromaz" />
</RelativeLayout>
</ScrollView>
setelah itu controlnya yaitu MainActivity.java
package com.example.demosavedata;
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.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity
{
EditText namax,alamatx,ttlx,pekerjaanx,gajix,tunjanganx,thrx;
TextView error;
Button simpan,edit,hapus,keluar;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
namax=(EditText)findViewById(R.id.editText2);
alamatx=(EditText)findViewById(R.id.editText1);
ttlx=(EditText)findViewById(R.id.editText3);
pekerjaanx=(EditText)findViewById(R.id.editText4);
gajix=(EditText)findViewById(R.id.editText5);
tunjanganx=(EditText)findViewById(R.id.editText6);
thrx=(EditText)findViewById(R.id.editText7);
simpan=(Button)findViewById(R.id.button1);
keluar=(Button)findViewById(R.id.button2);
keluar.setOnClickListener(exit);
simpan.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("nama", namax.getText().toString()));
postParameters.add(new BasicNameValuePair("alamat", alamatx.getText().toString()));
postParameters.add(new BasicNameValuePair("ttl", ttlx.getText().toString()));
postParameters.add(new BasicNameValuePair("pekerjaan", pekerjaanx.getText().toString()));
postParameters.add(new BasicNameValuePair("gaji", gajix.getText().toString()));
postParameters.add(new BasicNameValuePair("tunjangan", tunjanganx.getText().toString()));
postParameters.add(new BasicNameValuePair("thr", thrx.getText().toString()));
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://10.0.2.2/PhpProject1/simpan1.php", postParameters);
String res = response.toString();
res = res.trim();
res = res.replaceAll("\\s+","");
if (res.equals("1")) namax.setText("Data Tersimpan");
else
Toast.makeText(getBaseContext(), "data kesimpan di server",Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
Toast.makeText(getBaseContext(), ""+e.toString(),Toast.LENGTH_SHORT).show();
}
}
});
}
View.OnClickListener exit=new View.OnClickListener()
{
public void onClick(View v)
{
System.exit(1);
}
};
}
CustomHttpClient.java
package com.example.demosavedata;
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 CustomHttpClient
{
HttpClient httpClient;
HttpGet httpGet;
HttpResponse httpResponse;
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 30 * 9000000; // milliseconds
/** Single instance of our HttpClient */
private static HttpClient mHttpClient;
public CustomHttpClient()
{
httpClient=new DefaultHttpClient();
}
/**
* Get our single instance of our HttpClient object.
*
* @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;
}
/**
* Performs an HTTP Post request to the specified url with the
* specified parameters.
*
* @param url The web address to post the request to
* @param postParameters The parameters to send via the request
* @return The result of the request
* @throws Exception
*/
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();
}
}
}
}
/**
* Performs an HTTP GET request to the specified url.
*
* @param url The web address to post the request to
* @return The result of the request
* @throws Exception
*/
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();
}
}
}
}
public String get(String url) throws IOException{
httpGet=new HttpGet(url);
httpResponse=httpClient.execute(httpGet);
BufferedReader rd = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
String line = "";
StringBuilder builder=new StringBuilder();
while ((line = rd.readLine()) != null) {
builder.append(line);
}
return builder.toString();
}
}
terakhir adalah Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.demosavedata"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.demosavedata.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
karena koneksi ke internet/localhost, maka di manifest harus di beri tag :
<uses-permission android:name="android.permission.INTERNET" />
supaya bisa terkoneksi
untuk lebih lanjut bisa download projectnya di : android project
Komentar
Posting Komentar