ในการดึงข้อมูลจาก MySQL ในฝั่ง Server นั้นจะใช้ PHP ในการดึงข้อมูลและเปลียนให้อยู่ในรูปแบบของ JSON เพื่อสามารถที่จะนำมาใช้กับ Android ได้
Code ในส่วนของฐานข้อมูล MySQL (utf8_general_ci) :
CREATE TABLE `people` ( `id` int(11) NOT NULL, `name` varchar(100) NOT NULL, `sex` varchar(1) NOT NULL, `birthyear` int(11) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8; INSERT INTO `people` VALUES (0, 'นางดอกส้มสีทอง', 'F', 2010); INSERT INTO `people` VALUES (1, 'Slayer', 'M', 1991); INSERT INTO `people` VALUES (2, 'Petdo', 'M', 2011); INSERT INTO `people` VALUES (3, 'มนุษย์ต่างดาว', 'F', 1500);
Code ในส่วนของ PHP ในการดึงข้อมูลออกมาในรูปแบบของ JSON (แนะนำว่า Save แบบ ANSI เนื่องจากผมลอง UTF-8 แล้วมันส่งข้อมูลออกมามั่วนิดหน่อยทำให้ไม่สามารถทำงานได้) :
<?php
mysql_connect("host","username","password");
mysql_select_db("database");
//ดึงข้อมูลออกมาในรูปแบบ UTF 8
mysql_query("SET NAMES UTF8");
//ส่วนของ SELECT ข้อมูลจาก DataBase
$moreYear=$_REQUEST['moreYear'];
if(!$moreYear) $moreYear=0;
$q=mysql_query("SELECT * FROM people where birthyear > $moreYear");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
//แปลงข้อมูลให้อยู่ในรูปแบบของ JSON และพิมพ์ข้อมูลออกมา
print(json_encode($output));
mysql_close();
?>
XML ในส่วนของ View :
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_height="150px"
android:layout_width="300px"
android:text="JSON :"
android:id="@+id/txtJson"
android:layout_x="16dp"
android:layout_y="10dp" />
<TextView
android:layout_height="300px"
android:layout_width="300px"
android:text="RESULT :"
android:id="@+id/txtResult"
android:layout_x="16dp"
android:layout_y="147dp" />
</AbsoluteLayout>
XML ในส่วนของ AndroidManifest.xml (เพิ่มก่อน Tag application) :
<uses-sdk android:minSdkVersion="8" /> <uses-permission android:name="android.permission.INTERNET" />
Code ในส่วนของ JAVA :
package slayer.TestDB;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;
public class TestDBActivity extends Activity {
//กำหนดที่อยู่ของไฟล์ php ในการดึงข้อมูล
//หากใช้เครื่องที่รัน Emulator เป็น Server ให้ใช้ IP 10.0.2.2 (เครื่องเราเอง)
public static final String KEY_SERVER = "http://10.0.2.2/android/getData.php";
private TextView txtJson; //Text แสดงข้อมูล JSON
private TextView txtResult; //Text แสดงข้อมูลที่ได้จาก Server
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//เตรียม View
txtJson = (TextView) findViewById(R.id.txtJson);
txtResult = (TextView) findViewById(R.id.txtResult);
//ทำการดึงข้อมูลโดยใช้ฟังก์ชัน getServerData()
txtResult.setText("RESULT : \n" + getServerData());
}
private String getServerData() {
String returnString = "";
InputStream is = null;
String result = "";
//ส่วนของการกำหนดตัวแปรเพื่อส่งให้กับ php
//ส่วนนี้สามารถประยุกต์ไปใช้ในการเพิ่มข้อมูลให้กับ Server ได้
//จากตัวอย่างส่งค่า moreYear ที่มีค่า 1990
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//ส่งค่า POST DATA ให้ PHP
nameValuePairs.add(new BasicNameValuePair("moreYear", "1990"));
//ส่วนของการเชื่อมต่อกับ http เพื่อดึงข้อมูล
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(KEY_SERVER);
//update 17-11-2011 เข้ารหัส post เป็น utf-8 เพื่อไม่ให้มีปัญหากับภาษาไทย
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
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());
}
//ส่วนของการแปลงผลลัพธ์ให้อยู่ในรูปแบบของ String
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-11"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
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());
}
//ส่วนของการแปลงข้อมูล JSON ออกมาในรูปแบบของข้อมูลทั่วไปเพื่อนำไปใช้
try {
//แสดงผลออกมาในรูปแบบของ JSON
txtJson.setText("JSON : \n" + result);
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
//พิมพ์ Log ดูเพื่อป้องกันข้อผิดพลาด
Log.i("log_tag",
"id: " + json_data.getInt("id") + ", name: "
+ json_data.getString("name") + ", sex: "
+ json_data.getString("sex") + ", birthyear: "
+ json_data.getInt("birthyear"));
//นำข้อมูลใส่ตัวแปรเพื่อไปแสดงต่อ
returnString += "\nID : " + json_data.getInt("id")
+ "\nName : " + json_data.getString("name")
+ "\nSex : " + json_data.getString("sex")
+ "\nBirthyear: " + json_data.getInt("birthyear")
+ "\n";
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
//ส่งผลลัพธ์ไปแสดงใน txtResult
return returnString;
}
}
Credits : http://www.anddev.org/networking-database-problems-f29/connecting-to-mysql-database-t50063.html


ยอดเยี่ยมมากๆๆๆ ทำให้เข้าใจและเห็นภาพการทำงาน ครับ
ตอบลบอัพๆๆๆค่ะ....
ตอบลบขอบคุนนะค่ะ
ตอบลบผมทำได้ครับ แต่ว่า ภาษาไทยมันไม่มา
ตอบลบแต่ว่าสั่ง echo ในหน้า php แบบเอาออกมาดูแค่ฟิลเดียว ฟิลที่เป็นภาษาไทย มันก็เป็นภาษาไทยนะครับ แสดงว่า คำสั่ง select database ถูกใช่มั้ยครับ แต่เวลานำข้อมูลใส่ array มันกลายเป็นหายไป
เรวัด งามสลัก <<< (echo.อันนี้ดึงสด ฟิลเดียว)
[{"ServiceNO":"s0080000","ServiceDate":"2011-02-19 00:00:00","ServiceTime":"1899-12-30 14:51:51","CustomerID":"c025653",("CustomerName":"")<<(แต่ใน $output[] ดันไม่โชว์)
ทำไงดีครับผม Y_Y
แจ่มไปเลย ครับ
ตอบลบติดตามครับผทม
ตอบลบ