Hướng dẫn tích hợp google app engine vào ứng dụng android (P2)

I. GIỚI THIỆU

bài viết trước mình đã hướng dẫn các bạn cách cơ bản để xây dựng một backend trên google app engine.
Ở bài viết này mình sẽ hướng dẫn các bạn cách sử dụng những gì mà mình đã tạo ra.

II. NỘI DUNG BÀI VIẾT

  1. Sơ lượt cách sử dụng API , Test API bằng PostMan
  2. Sử dụng API trong ứng dụng Android.
    -Khai báo các API.
    -Triển khai các API.
    -Lên giao diện đơn giản.
    -Code presenter.
    -Build project.

III. Bắt đầu

  1. Sơ lượt cách sử dụng API và test API  trên postman

Đây là danh sách các  API trong bài viết trước của mình :
https://balmy-chain-154406.appspot.com

Test thử API insert: Link trên cloud

 

Test tiếp một API nữa: đây là API getlist nếu bạn muốn lấy toàn bộ chỉ cần bỏ phần limit phía sau:  Link trên cloud

Cơ bản là như vậy dữ liệu trả về dạng Json các bạn có thể đưa vào app dùng thư viện và quất nó ra.

2. Sử dụng API trong ứng dụng Android.

Tiếp tục mở project cũ ra ở đây mình tiếp tục sử dụng thư viện Retrofit 2 để thao tác với các API.  Thư viện Retrofit2
Trong project này mình sẽ triển khai 2 API là Create và Get List

    compile 'com.android.support:recyclerview-v7:25.1.0'
    compile 'com.jakewharton:butterknife:8.4.0'
    apt 'com.jakewharton:butterknife-compiler:8.4.0'
    compile 'com.squareup.retrofit2:retrofit:2.0.2'
    compile 'com.google.code.gson:gson:2.6.2'
    compile 'com.squareup.retrofit2:converter-gson:2.0.2'

Cấu trúc project áp dụng theo mô hình MVP:

  • Config.java : Khai báo các API
public class Config {
    public  static  final String BASE_URL = "https://balmy-chain-154406.appspot.com/_ah/api/employeeApi/v1/";
    //API
    public  static final String LIST_API = "employee";
    public  static final String CREATE_API = "employee";
}
  • Employee.java: Xây dựng đối tượng
public class Employee {
    @SerializedName("id")
    Long id;
    @SerializedName("employeeCode")
    String employeeCode;
    @SerializedName("fullName")
    String fullName;
    @SerializedName("phoneNumber")
    private int phoneNumber;

    public Employee() {
    }
    public static Employee getEmployee (JSONObject jsonObject){
        return new Gson().fromJson(jsonObject.toString(),Employee.class);
    }

    public  static ArrayList<Employee> getListEmployee (JSONArray jsonArray) throws JSONException {
        ArrayList<Employee> arrayList = new ArrayList<>();
        for(int i = 0; i<jsonArray.length(); i++) {
            arrayList.add(getEmployee(jsonArray.getJSONObject(i)));
        }
        return arrayList;
    }
// Contructor getter setter các bạn tự thêm nhé.
  • Viết các Interface trong listener
    OnCreateListener.java

    public interface OnCreateListener {
        void onFetchSuccess(JSONObject jsonObject);
        void onFetchFault(Exception e);
    }
    

    OnGetListListener.java

    public interface OnGetListListener {
        void onFetchSuccess(ArrayList<Employee> list);
        void onFetchFault(Exception e);
    }
    
  • Triển khai các API trong apihelpers:
    • Trong package createmployee
      CreateEmployeeApi.java

      public interface CreateEmployeeApi {
          @POST(Config.CREATE_API)
          Call<ResponseBody> createEmployee(@Body RequestBody body);
      }
      

      CreateEmployeeApiIml.java triển khai API ở trên

      public class CreateEmployeeApiIml extends BaseRetrofitIml {
      
          private CreateEmployeeApi createEmployeeApi;
      
          public CreateEmployeeApiIml() {
              createEmployeeApi = getRetrofit().create(CreateEmployeeApi.class);
          }
      
          public void createEmployee(Employee employee, final OnCreateListener listener) {
              Gson gson = new Gson();
              String json = gson.toJson(employee, Employee.class);
              final RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
              Log.d("abc", "createEmployee: "+ json);
              Call<ResponseBody> call = createEmployeeApi.createEmployee(body);
              call.enqueue(new Callback<ResponseBody>() {
                  @Override
                  public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                      if (response.isSuccessful()) {
                          try {
                              JSONObject jsonObject = new JSONObject(response.body().string());
                              listener.onFetchSuccess(jsonObject);
                              Log.d("abc", "onResponse: "+jsonObject.toString());
      
                          } catch (JSONException e) {
                              e.printStackTrace();
                          } catch (IOException e) {
                              e.printStackTrace();
                          }
                      }
                  }
      
                  @Override
                  public void onFailure(Call<ResponseBody> call, Throwable t) {
                     listener.onFetchFault(new Exception(t));
                  }
              });
      
          }
      
      
      }
    • Trong package listemployee
      GetListEmployeeApi.java

      public interface GetListEmployeeApi {
          @GET(Config.LIST_API)
          Call<ResponseBody> getListEmployee();
      }
      

      GetListEmployeeApiIml.java triển khai API ở trên

      public class GetListEmployeeApiIml extends BaseRetrofitIml {
          String TAG = GetListEmployeeApiIml.class.getSimpleName();
          private GetListEmployeeApi apiService;
          private Activity activity;
          public GetListEmployeeApiIml() {
              apiService = getRetrofit().create(GetListEmployeeApi.class);
          }
      
          public void getListEmployee(final OnGetListListener dataCallback) {
              Call<ResponseBody> getEmployee = apiService.getListEmployee();
              getEmployee.enqueue(new Callback<ResponseBody>() {
                  @Override
                  public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                      try {
                          JSONObject ob = new JSONObject(response.body().string());
                          JSONArray arr = ob.getJSONArray("items");
                          dataCallback.onFetchSuccess(Employee.getListEmployee(arr));
                      } catch (Exception e) {
                          dataCallback.onFetchFault(e);
                      }
                  }
      
                  @Override
                  public void onFailure(Call<ResponseBody> call, Throwable t) {
                      Log.e(TAG, t.toString());
                      dataCallback.onFetchFault(new Exception(t));
                  }
              });
          }
      
      }
  • Xây dựng giao diện trong package views

    • activity_list_riddle.xml

      <?xml version="1.0" encoding="utf-8"?>
      <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
          android:id="@+id/activity_list_riddle"
          android:layout_width="match_parent"
          android:layout_height="match_parent">
      
          <Button
              android:text="Get List Riddle"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:id="@+id/btnGetData"
              android:layout_alignParentLeft="true"
              android:layout_alignParentStart="true" />
          <Button
              android:text="CreateRiddle"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:id="@+id/btnCreateRiddle"
              android:layout_alignParentRight="true"
              android:layout_alignParentEnd="true" />
          <android.support.v7.widget.RecyclerView
              android:id="@+id/recyclerView"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:layout_centerHorizontal="true"
              android:layout_below="@+id/btnGetData" />
      </RelativeLayout>
      

       

    • activity_create_riddle.xml
      <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/apk/res-auto"
          xmlns:tools="http://schemas.android.com/tools"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:orientation="vertical">
      
          <TextView
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:gravity="center"
              android:paddingBottom="20dp"
              android:text="Create Employee"
              android:textSize="30sp" />
      
          <TextView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="Số điện thoại"
              android:textSize="20sp" />
      
          <EditText
              android:id="@+id/edt_phone"
              android:layout_width="match_parent"
              android:layout_height="wrap_content" />
      
          <TextView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="FullName"
              android:textSize="20sp" />
      
          <EditText
              android:id="@+id/edt_fullname"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:lines="4" />
      
      
          <TextView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="Mã Số"
              android:textSize="20sp" />
      
          <EditText
              android:id="@+id/edt_employcode"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:lines="2" />
      
      
          <LinearLayout
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:layout_marginTop="15dp"
              android:gravity="center"
              android:orientation="horizontal">
      
              <Button
                  android:id="@+id/btn_create"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:text="Create" />
      
              <Button
                  android:id="@+id/btn_cancel"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:text="Cancel" />
          </LinearLayout>
      
      </LinearLayout>
      
      
    • item_list.xml

      <?xml version="1.0" encoding="utf-8"?>
      <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical" android:layout_width="match_parent"
          android:layout_height="wrap_content">
          <LinearLayout
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:orientation="horizontal">
              <TextView
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:text="Code: "
                  android:textSize="18sp" />
              <TextView
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  android:layout_marginLeft="10dp"
                  android:id="@+id/tv_employeecode"
                  android:textSize="18sp" />
          </LinearLayout>
      
          <LinearLayout
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:orientation="horizontal">
              <TextView
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:text="Fullname: "
                  android:textSize="18sp" />
              <TextView
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  android:layout_marginLeft="10dp"
                  android:id="@+id/txt_fullname"
                  android:textSize="18sp" />
          </LinearLayout>
          <View
              android:layout_width="match_parent"
              android:layout_height="1dp"
              android:background="#000"/>
      </LinearLayout>

       

  • Tạo adapter để hiện thị dữ liệu: EmployeeAdapter.java
public class EmployeeAdapter extends RecyclerView.Adapter<EmployeeAdapter.EmployeeHolder> {
    ArrayList<Employee> listEmployee;
    Context context;

    public EmployeeAdapter(Context context, ArrayList<Employee> listEmployee) {
        this.context = context;
        this.listEmployee = listEmployee;
    }

    @Override
    public EmployeeHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list,parent,false);
        return new EmployeeHolder(view);
    }

    @Override
    public void onBindViewHolder(EmployeeHolder holder, int position) {
        Employee employee = listEmployee.get(position);
        holder.tv_employeecode.setText(String.valueOf(employee.getEmployeeCode()));
        holder.tv_fullName.setText(employee.getFullName());
    }

    @Override
    public int getItemCount() {
        return listEmployee.size();
    }

    class EmployeeHolder extends RecyclerView.ViewHolder{
        @BindView(R.id.tv_employeecode)
        TextView tv_employeecode;
        @BindView(R.id.txt_fullname)
        TextView tv_fullName;
        public EmployeeHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this,itemView);
        }
    }
}
  • Code presenter
    • CreateEmployeePresenter
      ublic class CreateEmployeePresenter {
          String TAG = CreateEmployeePresenter.class.getSimpleName();
          Activity activity;
          CreateEmployeeApiIml riddleApiIml;
      
          public CreateEmployeePresenter(Activity activity) {
              this.activity = activity;
              this.riddleApiIml = new CreateEmployeeApiIml();
          }
      
          public void createEmployeeData(Employee employee){
      
              riddleApiIml.createEmployee(employee, new OnCreateListener() {
                  @Override
                  public void onFetchSuccess(JSONObject jsonObject) {
                      Log.d("abcc", "onFetchSuccess: "  + jsonObject.toString());
                      Employee employee1 = Employee.getEmployee(jsonObject);
                      Toast.makeText(activity, employee1.toString(), Toast.LENGTH_SHORT).show();
                  }
      
                  @Override
                  public void onFetchFault(Exception e) {
                      Log.e(TAG,e.toString());
                  }
              });
          }
      }
    • ListEmployeePresenter.java
      public class ListEmployeePresenter {
          private EmployeeAdapter employeeAdapter;
          private ArrayList<Employee> employeeList = new ArrayList<>();
          private Activity activity;
          private GetListEmployeeApiIml apiServiceIml;
      
      
          public ListEmployeePresenter(Activity activity) {
              this.activity = activity;
              this.apiServiceIml = new GetListEmployeeApiIml();
          }
      
          /**
           * parse data
           * Noti adapter
           * */
          public void fetchData(final RecyclerView recyclerView) {
              apiServiceIml.getListEmployee(new OnGetListListener() {
                  @Override
                  public void onFetchSuccess(ArrayList<Employee> list) {
                      employeeList.clear();
                      employeeList.addAll(list);
                      employeeAdapter = new EmployeeAdapter(activity,employeeList);
                      recyclerView.setAdapter(employeeAdapter);
                      employeeAdapter.notifyDataSetChanged();
                  }
      
                  @Override
                  public void onFetchFault(Exception e) {
                      e.printStackTrace();
                  }
              });
          }
      }
  • Cuối cùng quay lại code 2 Activity
    • CreateEmployeeActivity.java
      public class CreateEmployeeActivity extends AppCompatActivity {
      
          CreateEmployeePresenter presenter;
          @BindView(R.id.edt_phone)
          EditText edtPhone;
          @BindView(R.id.edt_fullname)
          EditText edtFullname;
          @BindView(R.id.edt_employcode)
          EditText edtEmploycode;
      
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_create_riddle);
              ButterKnife.bind(this);
              presenter = new CreateEmployeePresenter(this);
      
          }
      
          @OnClick(R.id.btn_create)
          public void createEmployee() {
              Employee employee = new Employee();
              employee.setFullName(edtFullname.getText().toString());
              employee.setEmployeeCode(edtEmploycode.getText().toString());
              employee.setPhoneNumber(Integer.parseInt(edtPhone.getText().toString()));
              presenter.createEmployeeData(employee);
          }
          
      }
    • ListEmployeeActivity.java

      public class ListEmployeeActivity extends AppCompatActivity {
          @BindView(R.id.recyclerView)
          RecyclerView recyclerView;
          ListEmployeePresenter mainPresenter;
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_list_riddle);
              ButterKnife.bind(this);
               RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
              recyclerView.setLayoutManager(layoutManager);
              mainPresenter = new ListEmployeePresenter(this);
      
          }
          @OnClick(R.id.btnGetData)
          public void getData() {
              mainPresenter.fetchData(recyclerView);
          }
          @OnClick(R.id.btnCreateRiddle)
          public void show() {
              Intent intent = new Intent(this,CreateEmployeeActivity.class);
              startActivity(intent);
          }
      }

Vậy là đã hoàn thành project vơi 2 API là create và getList, mong rằng các bạn có thể nghiên cứu được nhiều thứ hơn và chia sẻ lại cho mình.
Download Source Code.

Nguyễn Linh

Chia sẻ để cùng tiến bộ...