สำนักวิทยบริการและเทคโนโลยีสารสนเทศ (สวส.)

Office of Academic Resources and Information Technology


Office of Academic Resources and Information Technology

Android ติดต่อ MySQL Server

ตัวมือถือหรือเทบเล็ต Android นั้น ไม่สามารถที่จะติดต่อ กับ mysql server ได้โดยตรง
แต่ทั้งนั้นเราสามารถเขียน code ให้เจ้า android ติดต่อ Mysql ผ่านตัวกลางที่เป็น  Server Side Script ได้
ในบทความนี้ผมจะใช้ PHP เป็นตัวกลางเพื่อทำให้เจ้า Android ติดต่อกับ MySQL ได้ ซึ่งสามารถที่จะสั่ง
insert,select,update  และ  delete  ตารางบน MySQL Server จากหน้าจอเครื่อง Android ของเราได้เลย
ก่อนอื่นเรามาดูไดอะแกรมของระบบครับ (ตามรูป)
จากนั้นเริ่มเขียน Code กันเลยครับ โดยทำตามขั้นตอนดังนี้
1) เปิด Eclipse ขึ้นมา ไปที่ File – New – Android Project และตั้งชื่อ Project ดังรูป
2) เลือก SDK
3)ตั้งชื่อ Package Name
4)แก้ไขไฟล์ /res/layout/main.xml ดังนี้
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Connect To Mysql Example" />
    <EditText
        android:id="@+id/txt_hn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="HN" >
    </EditText>
    <EditText
        android:id="@+id/txt_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Name-Lastname" />
    <EditText
        android:id="@+id/txt_age"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Age" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
        <Button
            android:id="@+id/btn_insert"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Insert" />
        <Button
            android:id="@+id/btn_select"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Select" />
        <Button
            android:id="@+id/btn_update"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Update" />
        <Button
            android:id="@+id/btn_delete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Delete" />
    </LinearLayout>
    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent" >
            <TextView
                android:id="@+id/tv_res"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="" />
        </LinearLayout>
    </ScrollView>
</LinearLayout>
5)แก้ไขไฟล์ /src/Main.java ดังนี้
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
package com.Example;
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.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
 
public class Main extends Activity implements OnClickListener {
 
 Button btn_select;
 Button btn_insert;
 Button btn_update;
 Button btn_delete;
 
 TextView tv_res;
 EditText txt_hn;
 EditText txt_name;
 EditText txt_age;
 
 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);
 // ตั้งค่าตัวแปล View
 tv_res = (TextView)findViewById(R.id.tv_res);
 txt_hn = (EditText)findViewById(R.id.txt_hn);
 txt_name = (EditText)findViewById(R.id.txt_name);
 txt_age = (EditText)findViewById(R.id.txt_age);
 
 btn_select = (Button)findViewById(R.id.btn_select);
 btn_select.setOnClickListener(this);
 
 btn_insert = (Button)findViewById(R.id.btn_insert);
 btn_insert.setOnClickListener(this);
 
 btn_update = (Button)findViewById(R.id.btn_update);
 btn_update.setOnClickListener(this);
 
 btn_delete = (Button)findViewById(R.id.btn_delete);
 btn_delete.setOnClickListener(this);
 
 }
 
 @Override
 public void onClick(View v){
 switch(v.getId()){
 case R.id.btn_select:
 {
 select();
 break;
 }
 case R.id.btn_insert:
 {
 insert();
 break;
 }
 case R.id.btn_update:
 {
 update();
 break;
 }
 case R.id.btn_delete:
 {
 delete();
 break;
 }
 }
 }
 
 public void clsText(){
 txt_hn.setText("");
 txt_name.setText("");
 txt_age.setText("");
 }
 
 public void insert(){
 try{
 String hn = txt_hn.getText().toString().trim();
 String name = txt_name.getText().toString().trim();
 String age = txt_age.getText().toString().trim();
 if ( hn.equals("") || name.equals("") || age.equals("") ){
 return ;
 }
 ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
 nameValuePairs.add(new BasicNameValuePair("isAdd","true"));
 nameValuePairs.add(new BasicNameValuePair("hn",hn));
 nameValuePairs.add(new BasicNameValuePair("name",name));
 nameValuePairs.add(new BasicNameValuePair("age",age));
 HttpClient httpclient = new DefaultHttpClient();
 HttpPost httppost = new HttpPost("http://10.0.2.2:82/php_set_data.php");//Change IP to you WebServer
 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
 httpclient.execute(httppost);
 clsText();
 }catch(Exception e){
 Log.d("log_err", "Error in http connection " + e.toString());
 }
 }
 
 public void update(){
 // Your update algorithm
 Toast.makeText(getApplicationContext(), "update",Toast.LENGTH_SHORT).show();
 }
 
 public void delete(){
 // Your delete algorithm
 Toast.makeText(getApplicationContext(), "delete",Toast.LENGTH_SHORT).show();
 }
 
 public void select() {
 tv_res.setText("");
 InputStream is = null;
 String js_result = "";
 try {
 HttpClient httpclient = new DefaultHttpClient();
 HttpPost httppost = new HttpPost("http://10.0.2.2:82/php_get_data.php");
 HttpResponse response = httpclient.execute(httppost);
 HttpEntity entity = response.getEntity();
 is = entity.getContent();
 } catch (Exception e) {
 Log.d("log_err", "Error in http connection " + e.toString());
 }
 try {
 BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
 StringBuilder sb = new StringBuilder();
 String line = null;
 while ((line = reader.readLine()) != null) {
 sb.append(line);
 }
 is.close();
 js_result = sb.toString();
 } catch (Exception e) {
 Log.e("log_tag", "Error converting result " + e.toString());
 }
 try {
 final JSONArray jArray = new JSONArray(js_result);
 for (int i = 0; i < jArray.length(); i++) {
 JSONObject jo = jArray.getJSONObject(i);
 String hn = jo.getString("hn");
 String name = jo.getString("name");
 String age = String.valueOf(jo.getInt("age"));
 String date_serv = jo.getString("date_serv");
 Log.d("log",hn+","+name+","+age+","+date_serv);
 tv_res.append(hn+","+name+","+age+","+date_serv+"\n");
 }
 } catch (JSONException e) {
 Log.e("log_tag", "Error parsing data " + e.toString());
 }
}
}
6)แก้ไขไฟล์ AndroidManifest.xml ดังนี้
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0" encoding="utf-8"?>
 package="com.Example"
 android:versionCode="1"
 android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
 <uses-permission android:name="android.permission.INTERNET" />
<application
 android:icon="@drawable/ic_launcher"
 android:label="@string/app_name" >
 <activity
 android:name=".Main"
 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>
ซึ่งตอนนี้เราได้สร้าง Application ฝั่ง Android เรียบร้อยแล้ว
ขั้นตอนต่อไปเราต้องไปสร้าง Application ฝั่ง Server ก็คือ ไฟล์ PHP ของเรานั่นเองครับ
ในบทความนี้ผมสร้าง PHP ขึ้นมา 2 ไฟล์ คือ
- ไฟล์ php_set_data.php ทำหน้าที่ insert
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
header("content-type:text/javascript;charset=utf-8");
$con=mysql_connect('localhost','sa','sa')or die(mysql_error());   // เปลี่ยน localhost เป็น ip ของ mysql server
mysql_select_db('android')or die(mysql_error());
mysql_query("SET NAMES UTF8");
if (isset($_POST)){
    if($_POST['isAdd']=='true'){
        $hn=$_POST['hn'];
        $name=$_POST['name'];
        $age = $_POST['age'];
        $date = date('Y-m-d');
        $sql="INSERT INTO `patient` (`hn`, `name`, `age`, `date_serv`) VALUES ('$hn', '$name', '$age', '$date')";
        mysql_query($sql);
    }
}
mysql_close();
?>
-ไฟล์ php_get_data.php ทำหน้าที่ select
1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
header("content-type:text/javascript;charset=utf-8");
$con=mysql_connect('localhost','sa','sa')or die(mysql_error());  // เปลี่ยน localhost เป็น ip ของ mysql server
mysql_select_db('android')or die(mysql_error());
mysql_query("SET NAMES UTF8");
$sql="SELECT * FROM patient";
$res=mysql_query($sql);
while($row=mysql_fetch_assoc($res)){
    $output[]=$row;
}
print(json_encode($output));
mysql_close();
?>
จากนั้นไปที่ Mysql Server ให้ท่านสร้าง database ชื่อ android ขึ้นมา
และให้ create table ชื่อ patient ด้วยคำสั่งดังนี้
1
2
3
4
5
6
7
8
9
10
11
12
13
DROP TABLE IF EXISTS `patient`;
CREATE TABLE `patient` (
  `hn` varchar(9) DEFAULT '',
  `name` varchar(100) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `date_serv` varchar(80) DEFAULT '0000-00-00'
) ENGINE=InnoDB DEFAULT CHARSET=tis620;
 
-- ----------------------------
-- ทดสอบใส่ข้อมูล 2 row
-- ----------------------------
INSERT INTO `patient` VALUES ('333', 'กกกกก', '12', '0000-00-00');
INSERT INTO `patient` VALUES ('222', 'aasss', '45', '0000-00-00');
เมื่อเสร็จสิ้นขั้นตอนทางฝั่ง Server แล้ว กลับไปที่ Eclipse แล้วลองรันโปรเจค TestMySql ดูครับ