[Android] Cara Insert MySQL Database via Android dengan AsyncTask

Kenapa Harus AsyncTask?, karena pada android 2,3 ke atas pengaksesan via httprequest tidak diperbolehkan langsung dari main UI. AsyncTask ini memungkinkan pengaksesan internet alias background databerjalan di background.

Langsung aja deh, pertama tentu kita bikin databasenya dulu

Create database mahasiswa;

CREATE TABLE  `mahasiswa` (
  `kd_mhs` int(11) NOT NULL AUTO_INCREMENT,
  `nim` varchar(14) NOT NULL,
  `nama` varchar(50) NOT NULL,
  `prodi` varchar(25) NOT NULL,
  PRIMARY KEY (`kd_mhs`)
);

lalu kita bikin file PHP nya buat ngehubungin android sama mysqlnya, gini source codenya

<?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 mahasiswa (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);
	}

?>

setelah itu edit layout nya seperti ini

<?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>

untuk file Javanya kayak gini

package com.mahasiswaapps;

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.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
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(), "Sukses broo!!!", Toast.LENGTH_LONG).show();
			} 
			else 
			{
				Toast.makeText(getApplicationContext(), "Gagal Bro!!!", Toast.LENGTH_LONG).show();

			}
		}
	}
}

untuk JSON nya kayak gini

package com.mahasiswaapps;

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;

	}
}

yang terakhir jangan lupa menambahkan uses-permission di android manifestnya, jadinya seperti ini

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mahasiswaapps"
    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.mahasiswaapps.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>

sekarang tinggal running, kalo bener pasti hasilnya kayak gini bro;

insert sukses insert sukses db

 

Download Source Code nya disini

 

3 thoughts on “[Android] Cara Insert MySQL Database via Android dengan AsyncTask

Leave a Reply

Your email address will not be published. Required fields are marked *


7 + = 12

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>