Hướng dẫn php android - php android

I. Thiết lập server với apache và php

1, Cài đặt

Lập trình Android liên kết với server(localhost) Để thiết lập một server trên windown bằng php có rất nhiều cách, ở đây ta sử dụng cách đơn giản nhất là down load và cài đặt Xampp. (Tham khảo: http://topthuthuat.com/huong-dan/huong-dan-cai-dat-xampp-de-tao-web-localhost). Phần mềm Xampp tích hợp sẵn các ứng dụng cần thiêt như Apache, PHP, MySQL

Cấu hình thư mục chứa các file php:

Vào thư mục “C:\xampp\apache\conf” (khi cài xampp mặc định) thay đổi nội dung file httpd.conf VD:

Alias /reports "D:/MonthlyReport/09-2014/"
<Directory "D:/MonthlyReport/09-2014/">
    Options Indexes MultiViews
    AllowOverride None
    Require all granted
</Directory>

Ta có thể truy cập vào http://localhost/reports ở đây ta sẽ thấy các thư mục, file chứa trong folder “D:/MonthlyReport/09-2014/”

Lưu ý: Khi thay đổi bất cứ gì ở file httpd.conf ta đều phải khởi động lại apache để có hiệu lực. Có thể bật “XAMPP Control Panel” clik vào stop sau đó start bên phải tên Apache.

2, Tạo database

Để tạo cơ sở dữ liệu, bạn có thể sử dụng phpMyAdmin để tạo một cách khá đơn giản và trực quan. Chi tiết, tham khảo tại http://topthuthuat.com/huong-dan/huong-dan-cai-dat-xampp-de-tao-web-localhost"

Ở đây, ta sử dụng các câu truy vấn mysql để tạo dữ liệu (tham khảo http://dev.mysql.com/doc/refman/5.5/en/sql-syntax-data-definition.html)

  • Tạo database có tên là “db_reports”:
CREATE DATABASE IF NOT EXISTS db_reports;
  • Tạo bảng dữ liệu với tên là “framgia_members” gồm các cột id-string, name-string, join_date-date:
CREATE TABLE IF NOT EXISTS framgia_members( id VARCHAR (10), name VARCHAR(255), join_date DATE );
  • Insert data:
INSERT INTO framgia_members (id, name, join_date)
VALUES ('B120002','Vu Xuan Dung','2011-11-21'),
('B120003','Tran Thi Ngoc Bich','2012-04-01'),
('B120005','Le Dinh Vu','2011-06-01'),
('B120006','Nguyen Thanh Linh','2011-12-01'),
('B120007','Le Van Nghia','2012-09-01');

3, Tạo file php để truy vấn dữ liệu trong database

Tạo file result.php để trả về dữ liệu là bảng “framgia_members” dưới dạng json. Nội dung file:


    $connect = mysql_connect("localhost","root","levanban");
    mysql_select_db('db_reports', $connect);
    $sql=mysql_query("select * from framgia_members");
    if($sql === FALSE) {
        die(mysql_error()); // TODO: better error handling
    }
    while($row=mysql_fetch_assoc($sql))
        $output[]=$row;
    print(json_encode($output));
    mysql_close();
?>

Trong đó, ta có các hàm có sẵn của php:

mysql_connect("localhost","root","levanban");

Connect tới mysql của localhost với user “root” pass: “levanban”

mysql_select_db('db_reports', $connect);

chọn database để truy vấn. mysql_query(“…”) trả về kết quả của query.

Như vậy, ta đã thiết lập xong server hay 1 url để truy cập dữ liệu trên server vào lấy kết quả dạng json. Với dữ liệu như trên khi truy cập vào http://localhost/reports/result.php ta được kết quả

[{"id":"B120002","name":"Vu Xuan Dung","join_date":"2011-11-21"},{"id":"B120003","name":"Tran Thi Ngoc Bich","join_date":"2012-04-01"},{"id":"B120005","name":"Le Dinh Vu","join_date":"2011-06-01"},{"id":"B120006","name":"Nguyen Thanh Linh","join_date":"2011-12-01"},{"id":"B120007","name":"Le Van Nghia","join_date":"2012-09-01"}]

II, Kết nối giữa Android và server(localhost)

Cách kết nối và lấy dữ liệu từ server dạng json để sử dụng với Android.

Lưu ý: Khi sử dụng localhost làm server ta thay localhost hay 127.0.0.1 bằng 10.0.2.2 để truy cập vào server.

  • Bước 1: Lấy nội dung của một respone trả về (http://10.0.2.2/reports/result.php)
InputStream iStream = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
iStream = entity.getContent();

Ở trên là các câu lệnh để lấy nội dung từ một respone đẩy vào một InpurStream để đọc dữ liệu.

  • Bước 2: Đọc dữ liệu từ InputStream đó đẩy vào String
String result = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"),8);
  sb = new StringBuilder();
  String line="0";
  while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
  }
  is.close();
  result=sb.toString();
  • Bước 3: Đẩy String nhận được vào JSONArray và lấy các dữ liệu cần thiết. VD:
CREATE DATABASE IF NOT EXISTS db_reports;
0

III, Hình ảnh demo của ứng dụng

Truy cập http://localhost/reports/result.php

http://tech.blog.framgia.com/vn/wp-content/uploads/2014/09/result-300x68.png

Ứng dụng Android chay với một service chạy ngầm, cứ 5s lại request tới server lấy dữ liệu vào hiện thị lên màn hình rồi biến mất.

Khi chạy ứng dụng với dữ liệu mẫu:

http://tech.blog.framgia.com/vn/wp-content/uploads/2014/09/fist_data-202x300.png

Khi thêm dữ lệu với dòng lệnh

CREATE DATABASE IF NOT EXISTS db_reports;
1

http://tech.blog.framgia.com/vn/wp-content/uploads/2014/09/second_data-202x300.png