kali ini kita mencoba membuat koneksi http post pada android

skenarionya
aplikasi ini akan menginsert atau menambah data pada server menggunakan metode POST
menu pada aplikasi :
- tambah data : untuk menambah data
- lihat data :untuk melihat data yang telah di tambah
jangan lupa tambahkan permission android.permission.INTERNET pada android manifest caranya
klik add | uses permission kemudian di kolom name bagian kanan pilih android.permission.INTERNET
file databasenya nama databasenya androidpost
CREATE TABLE IF NOT EXISTS `negara` (
`id_negara` int(11) NOT NULL AUTO_INCREMENT,
`negara` varchar(100) NOT NULL,
PRIMARY KEY (`id_negara`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;
file phpnya
tampil.php
<?php
$link = mysql_connect('localhost', 'root', '') or die('Cannot connect to the DB');
mysql_select_db('androidpost', $link) or die('Cannot select the DB');
$sql=mysql_query("select * from negara ");
while($row=mysql_fetch_assoc($sql)) $output[]=$row;
print(json_encode($output));
mysql_close();
?>
tambah.php
<?php
$negara = $_POST['negara'];
$link = mysql_connect('localhost', 'root', '') or die('Cannot connect to the DB');
mysql_select_db('androidpost', $link) or die('Cannot select the DB');
/* grab the posts from the db */
$query = "insert into negara (negara) values('".$negara."')";
$result = mysql_query($query, $link) or die('Error query: '.$query);
echo "sukkkk";
?>
file insert.java
package com.example.post_android;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class insert extends Activity {
private EditText tambah;
private Button tambah_btn;
/**
* Method yang dipanggil pada saat aplikaasi dijalankan
* */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tambah);
tambah = (EditText) findViewById(R.id.tambah);
tambah_btn = (Button) findViewById(R.id.tambah_btn);
//beri perintah
tambah_btn.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
eksekusi();
}
});
}
public void eksekusi() {
try {
HttpClient client = new DefaultHttpClient();
//kita mencoba di localhost
String postURL = "http://10.0.2.2/postandroid/tambah.php";
HttpPost post = new HttpPost(postURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("negara",tambah.getText().toString()));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
if (resEntity != null) {
Toast.makeText(this,"Sukses "+EntityUtils.toString(resEntity), Toast.LENGTH_SHORT).show();
}
} catch (Exception ex) {
Toast.makeText(this, "Tambah Data Gagal !", Toast.LENGTH_SHORT)
.show();
}
}
}
file lihat.java
package com.example.post_android;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.net.ParseException;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.app.Activity;
public class lihat extends ListActivity {
List<String> fd_id=new ArrayList<String>();
List<String> fd_name=new ArrayList<String>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.lihat);
String result = null;
InputStream is = null;
StringBuilder sb=null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/postandroid/tampil.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//try parse the string to a JSON object
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
fd_id.add(json_data.getString("id_negara"));
fd_name.add(json_data.getString("negara"));
}
}catch(JSONException e1){
Toast.makeText(getBaseContext(), "Data Tidak ditemukan", Toast.LENGTH_LONG).show();
}catch (ParseException e1){
e1.printStackTrace();
}
setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,fd_name));
}
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l,v,position, id);
String negara = ""+ fd_name.get(position);
String idnya = ""+ fd_id.get(position);
Toast.makeText(this, "name:"+negara+" id:"+idnya, 1).show();
}
}
file MainActivity.java
package com.example.post_android;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
String[] menu = new String[] { "Tambah Data", "Tampilkan Data"};
this.setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, menu));
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// Get the item that was clicked
Object o = this.getListAdapter().getItem(position);
String pilihan = o.toString();
tampilkanPilihan(pilihan);
}
protected void tampilkanPilihan(String pilihan) {
try {
Intent i = null;
if (pilihan.equals("Tambah Data")) {
i = new Intent(this, insert.class);
} else if (pilihan.equals("Tampilkan Data")) {
i = new Intent(this, lihat.class);
}
startActivity(i);
} catch (Exception e) {
e.printStackTrace();
}
}
}
file tambah.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" >
<EditText
android:id="@+id/tambah"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="@+id/tambah_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tambah" />
</LinearLayout>
file lihat.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" >
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawSelectorOnTop="false"
android:background="#3b3b3b">
</ListView>
<TextView
android:id="@android:id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@android:style/TextAppearance.Large"
android:gravity="center"
android:text="Data tidak ditemukan">
</TextView>
</LinearLayout>
file MainActivity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Button
android:id="@+id/lihat_data"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/tambah_data"
android:text="Lihat data" />
<Button
android:id="@+id/tambah_data"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Tambah Data" />
</RelativeLayout>
download kodenya
untuk file phpnya letakkan di folder postandroid
semoga berguna 🙂