Webservice trong android là gì
Home » Android » Tạo Web Service bằng PHP và MYSQL cho ứng dụng di động Part 1 Show
Tạo Web Service bằng PHP và MYSQL cho ứng dụng di động Part 1 NTC 24/03/201716/08/2019Android, Android Tutorial7 Comments on Tạo Web Service bằng PHP và MYSQL cho ứng dụng di động Part 1 Trong bài viết này mình sẽ hướng dẫn các bạn tạo Web Service bằng PHP và MYSQLđơn giản, cơ bản cho những bạn mới bắt đầu tìm hiểu về web service và PHP, cụ thể là web service trong android và hướng dẫn parse json bằng thư viện retrofit với web service đã tạo.Bạn đã từng nghe về web servicechưa, web service là gì và cách hoạt động của nó như thế? Web services là gì ?Web service là một tập các phương thức được gọi thực hiện từ xa thông qua một địa chỉ http url. Kết quả trả về của web service thường dưới dạng json hoặc xml. Web service thường được sử dụng để tạo các ứng dụng phân tán. Web service cho phép bạn giao tiếp qua mạng, không phải P2P. Nó cung cấp API cho phép bạn sử dụng nó để tương tác với service hoặc bạn có thể tự tạo web service bằng PHP và MYSQL như trong bài viết này. Đặc điểm của web service
frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen> Tạo web service bằng PHP và MYSQLTrước tiên để tạo web service bằng php và mysql thì bạn cần phải có server hỗ trợ ngôn ngữ php và mysql. Nếu bạn nào có chưa có hosting thì có thể tạo localhost với Xampp hoặc WampServer, các bạn không nên sử dụng hosting free vì những hosting free thường có chứa quảng cáo, khi bạn code trả về Json nó thường kèm theo các quảng cáo này gây khó khăn cho chúng ta trong việc xử lý. Trong hướng dẫn này mình dùng WampServer. B1:Tạo một database là students_managervà bảng là studentsbao gồm các trường : id, name, age, nclass. Sau khi cài wampserver thành công bạn vào đường dẫnhttp://localhost/phpmyadmin, user là root, pass để trống, chọn tab SQL và pase vào đoạn code sau. #Create database CREATE DATABASE students_manager; #Create Table students CREATE TABLE students_manager.students( `id` INT(10) NOT NULL AUTO_INCREMENT, `name` VARCHAR(50) NOT NULL, `age` INT(5) NOT NULL, `nclass` VARCHAR(10) NOT NULL, PRIMARY KEY(`id`) ) ENGINE = InnoDB DEFAULT CHARSET = utf8 AUTO_INCREMENT = 1; #Insert data INSERT INTO students_manager.students(`id`, `name`, `age`, `nclass`) VALUES (1, 'Nguyễn Văn A', '20', 'KT10'), (2, 'Nguyễn Văn B', '21', 'DT5'), (3, 'Nguyễn Văn C', '20', 'KT10'), (4, 'Nguyễn Văn D', '21', 'DT5'), (5, 'Nguyễn Văn E', '21', 'CK2')B2: Tạo file php đặt tên là api.phpđể file này trong thư mục www của WampServerC:wamp64wwwstudent_managerapi.php
Bạn vào đường dẫn sau để xem kết quả:http://localhost/student_manager/api.php. Hoặc các bạn có thể cài ứng dụng Postmannày trên chrome để có thể tùy biến xem kết quả dễ hơn, link trên trình duyệt chỉ có thể sử dụng được phương thức GET nhưng trên app này có thể sử dụng được nhiều phương thức khác nữa: GET, POST, PUT, PATCH, DELETE rất hữu ích. Xin lỗi các bạn vì có thể bạn thấy trong hình có trường class, nhưng trong sql thì không có, lý do là mình vừa sửa lại database 1 chút thành nclass :D.
Bạn chỉnh sửa thêm trong file api.php cho giống như dưới = 1) { while ($row = mysql_fetch_assoc($resouter)) { $temparray[] = $row; } } echo json_encode($temparray); end: ?>Để xem kết quả bạn chỉ cần thêm ?id=vào sau link lúc nãyhttp://localhost/student_manager/api.php?id=1. Nếu bạn để id trống http://localhost/student_manager/api.php?id=nó sẽ trả vềVui lòng nhập id. Sau khi đã có Json bạn có thể parse json bằng retrofit trong android mình đã nói ở bài trước. Json parsing with RetrofitB1:Mở Android studiovà tạo một project mới đặt tên WebServiceB2:Thêm thư viện retrofit vào dependencies (Module: app)dependencies { ... // Retrofit compile 'com.squareup.retrofit2:retrofit:2.2.0' // JSON Parsing compile 'com.google.code.gson:gson:2.8.0' compile 'com.squareup.retrofit2:converter-gson:2.2.0' ... }B3:Thêm quyền truy cập INTERNET vàoAndroidManifest.xmlB4:Tạo layout cho activity_main.xmlB5:Tạo Object class đặt tên Student và để trong package modelsCác thuộc tính của class Student giống y chang như các trường của database, cái hạn chế của parse json bằng Retrofit nó nằm ở đấy, tổ chức cấu trúc của Json như thế nào thì trong đối tượng trong Android phải y như thế đấy. Mình mới nghiên cứu cái thư viện này thấy như thế, không biết là có pro nào làm việc nhiều với thư viện này có cách xử lý khác không rất mong được chỉ giáo, xin cảm ơn rất nhiều. Cũng vì lý do này nên mình mới sửa class > nclass, do lúc đầu mình tạo database là class nên đối tượng trong android cũng phải đặt theo class. Mà đặt tên thuộc tính của đối tượng là class trong android là không được phép, sẽ thông báo lỗi ngay, mà chỉ sửa class > nclass trong android thì sẽ không parse được trường class trên webservice. Nên chỉ sửa 1 chút trên database với trong android là ok. package com.dev4u.ntc.webservice.models; /** * IDE: Android Studio * Created by Nguyen Trong Cong - NTCDE.COM * Name packge: com.dev4u.ntc.webservice.models * Name project: WebService * Date: 3/24/2017 * Time: 17:47 */ public class Student { private int id; private String name; private int age; private String nclass; public Student(int id, String name, int age, String nclass) { this.id = id; this.name = name; this.age = age; this.nclass = nclass; } @Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + ''' + ", age=" + age + ", nclass='" + + ''' + '}'; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getNclass() { return nclass; } public void setNclass(String nclass) { this.nclass = nclass; } }B6: Tạo classRetrofitClientĐể sử dụng các yêu cầu mạng đến một RESTful API bằng Retrofit, chúng ta cần tạo ra một đối tượng bằng cách sử dụng lớp Retrofit Builder và cấu hình nó với một URL cơ sở. package com.dev4u.ntc.webservice.webservice; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; /** * IDE: Android Studio * Created by Nguyen Trong Cong - NTCDE.COM * Name packge: com.dev4u.ntc.webservice * Name project: WebService * Date: 3/24/2017 * Time: 17:52 */ public class RetrofitClient { private static Retrofit retrofit = null; public static Retrofit getClient(String baseUrl) { if (retrofit == null) { retrofit = new Retrofit.Builder() .baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create()) .build(); } return retrofit; } }B7:Tạo API InterfaceTạo API Interface đặt tên là APIService. Interface này dùng đểchứa các phương thức mà chúng ta sẽ sử dụng để gọicác yêu cầu truy vấn HTTP chẳng hạn như GET, POST, PUT, và DELETE. Ở APIService Interface này, chỗgetStudent(@Query(id) String id) sẽ dùng phương thức@Query của thư viện Retrofit để truy vấn dữ liệu ở ?id=..theo như link trên browser là http://localhost/student_manager/api.php?id=.., ví dụ bạn muốn lấy student theo id và lớp chẳng hạn, bạn sẽ viết thành getStudent(@Query(id) String id, @Query(nclass) String nclass) , link trên browser sẽ làhttp://localhost/student_manager/api.php?id=?nclass= Ở đây còn một vấn đề nữa, Call
B8: Tạo classApiUtilsClassApiUtils dùng để khởi tạo Retrofit trong MainActivity và gọi các phương thức trong InterfaceAPIService. Ở đây mình chạy trên Emulator nên url mình để làhttp://10.0.2.2 còn nếu bạn chạy trên Genymotion sẽ đổi thànhhttp://10.0.2.3 package com.dev4u.ntc.webservice.webservice; /** * IDE: Android Studio * Created by Nguyen Trong Cong - NTCDE.COM * Name packge: com.dev4u.ntc.webservice * Name project: WebService * Date: 3/24/2017 * Time: 17:54 */ public class ApiUtils { public static final String BASE_URL = "http://10.0.2.2"; private ApiUtils() { } public static APIService getAPIService() { return RetrofitClient.getClient(BASE_URL).create(APIService.class); } }B8: Khởi tạo layout và Retrofit trong MainActivityprivate Button btnGetStudent; private Button btnGetStudents; private TextView tvResult; private APIService mAPIService; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } private void initView() { btnGetStudent = (Button) findViewById(R.id.btnGetStudent); btnGetStudents = (Button) findViewById(R.id.btnGetStudents); tvResult = (TextView) findViewById(R.id.tvResult); mAPIService = ApiUtils.getAPIService(); btnGetStudent.setOnClickListener(this); btnGetStudents.setOnClickListener(this); }B9: Set sự kiện OnClick cho 2 Button@Override public void onClick(View v) { switch (v.getId()) { case R.id.btnGetStudent: getStudentById(); break; case R.id.btnGetStudents: getAllStudents(); break; } } private void getAllStudents() { mAPIService.getStudents().enqueue(new Callback
Code file MainActivity package com.dev4u.ntc.webservice; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.dev4u.ntc.webservice.models.Student; import com.dev4u.ntc.webservice.webservice.APIService; import com.dev4u.ntc.webservice.webservice.ApiUtils; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Button btnGetStudent; private Button btnGetStudents; private TextView tvResult; private APIService mAPIService; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } private void initView() { btnGetStudent = (Button) findViewById(R.id.btnGetStudent); btnGetStudents = (Button) findViewById(R.id.btnGetStudents); tvResult = (TextView) findViewById(R.id.tvResult); mAPIService = ApiUtils.getAPIService(); btnGetStudent.setOnClickListener(this); btnGetStudents.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnGetStudent: getStudentById(); break; case R.id.btnGetStudents: getAllStudents(); break; } } private void getAllStudents() { mAPIService.getStudents().enqueue(new Callback
Xem hướng dẫnTạo Web Service bằng PHP và MYSQL cho ứng dụng di động Part 2 Project on Github:https://github.com/trongcong/WebServiceAndroid Json parsing, Parse json trong android, Parse Json với Retrofit, Tạo web service, Web service android, Webservice với PHP |