Akhirnya bisa juga menginput ke database mysql menggunakan android, :-D kali ini saya akan bercerita dikit nih, jadi saat menginput, mengedit, atau menghapus suatu data yang tersimpan dalam database (SQL) menggunakan android, maka urutan prosesnya dalah sebagai berikut :
ANDROID (Device) -> PHP (Web Server) -> SQL
![]() |
Skema Proses Input Data menggunakan JSON |
Untuk Android ke PHP ini dibutuhkan translater bahasa yang dalam hal ini adalah JSON. jadi JSON ini berfungsi untuk mentranslatekan bahasa pemrograman satu ke bahasa pemrograman lain, semisal dari java di hubungkan ke php, maka yang bertindak untuk menjembatani adalah JSON ini.
Oke, langsung ke programnya ya :-)
1. Pertama-tama buatlah Databasenya dulu.
Create database mahasiswa;
CREATE TABLE `mahasiswa`.`biodata`
`nim` varchar(14) NOT NULL,
`nama` varchar(50) NOT NULL,
`prodi` varchar(25) NOT NULL,
PRIMARY KEY (`nim`)
);
2. Kemudian buatlah tampilan program androidnya seperti berikut :
<?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">
<EditText
android:id="@+id/nim"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:hint="NIM"
android:paddingRight="10dp" />
<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="Nama"
/>
<EditText
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="@+id/prodi"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:paddingRight="10dp"
android:hint="Prodi"/>
<Button
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="@+id/btnsubmit"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:paddingRight="10dp"
android:text="submit"
/>
</LinearLayout>
</ScrollView>
</LinearLayout>
3. Kemudian Buat Class JSONParser.java
package com.isrul.cobajson;
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);
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) {
// 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 {
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;
}
}
4. pada MainActivity.java ubah seperti ini :
package com.isrul.cobajson;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText nim,nama,prodi;
Button submit;
JSONParser jParser = new JSONParser();
ProgressDialog pDialog;
private static String url = "http://10.0.2.2/insert/insert.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nim = (EditText)findViewById(R.id.nim);
nama= (EditText)findViewById(R.id.nama);
prodi=(EditText)findViewById(R.id.prodi);
submit = (Button)findViewById(R.id.btnsubmit);
submit.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View arg0) {
new input().execute();
}
});
}
@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;
}
public class input extends AsyncTask<String, String, String>
{
String success;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Lagi Proses bro...");
pDialog.setIndeterminate(false);
pDialog.show();
}
@Override
protected String doInBackground(String... arg0) {
String strNIM = nim.getText().toString();
String strNama = nama.getText().toString();
String strProdi = prodi.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("nim", strNIM));
params.add(new BasicNameValuePair("nama", strNama));
params.add(new BasicNameValuePair("prodi", strProdi));
JSONObject json = jParser.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(), "Simpan Sukses", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "Data Gagal Diinput", Toast.LENGTH_LONG).show();
}
}
}
}
5. Jangan lupa tambahkan sedikit pengaturan yang ada di AndroidManifest-nya
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.isrul.cobajson"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<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.isrul.cobajson.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>
6. Dan yang terakhir tambahkan insert.php yang disimpan di C:\xampp\htdocs\insert\insert.php
<?php
$conn = mysql_connect("localhost","root","");
mysql_select_db("mahasiswa");
$NIM = $_POST['nim'];
$NAMA= $_POST['nama'];
$PRODI = $_POST['prodi'];
header('Content-Type: text/xml');
$query = "insert into biodata (nim, nama, prodi) values ('$NIM','$NAMA','$PRODI')";
$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);
}
?>
gan codingan insert.php nya dong, tolong hehe
ReplyDeleteDicoba gan, rada lupa dah lama gk main android lagi :D
DeleteUdah saya tambahin di langkah terakhir
admin..saya sudah mengikuti cara yang ada, tidak ada yg error kenapa ketika di run selalu four close???
ReplyDeleteMungkin pada android manifest, cba dicek lgi.
Deletegan ane lgi butuh teori ttg skema input yg pke jsonnya..bisa berbagi gak gan teori ttg skemanya dapet dari sumber apa?makasih
ReplyDeleteMaaf ini saya dapat dari buku pemrograman android, disitu hanya berisi penjelasan proses inputnya bukan JSON-nya. dan untuk penjelasan proses kira2 sudah saya paparkan sedikit di paragraf ke 2 dan pada gambar
Deletegan import org.apache nya kk error itu kenapan gan?
ReplyDeletegan kalau eror nya itu yang import dibawah ini gmna gan?
ReplyDeleteimport org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;