Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 端透過後端接口取得資料庫資料( Gson 解析實戰)

編輯:關於 Android 程式設計

網上搜了一圈沒找到合適的說明,於是把自己剛學會的這套做法整理出來。核心概念其實很單純:後端提供一份接口文件,Android 端把參數 POST 過去,再把回傳的 JSON 用 Gson 反序列化成 Java 物件。實務上最常見的有兩種情境。

情境一:接口只回傳簡單的狀態值(以登入為例)

登入接口的請求參數大致如下:

伺服器回傳的結構:

回傳的欄位很多,但登入只需要用到 userInfo 裡的 phoneNum 與 userPsw(帳號與密碼)。

做法是把 userInfo 抽成一個類別,類別名稱最好與接口中定義的一致:

UserInfo.java(基本上就是一堆欄位加上 getter / setter 與建構子)

package xxxxxxx;

public class UserInfo {

    public UserInfo(int userId, String userName, String phoneNum,
                    String address, String userPsw, String picAddr) {
        this.userId = userId;
        this.userName = userName;
        this.phoneNum = phoneNum;
        this.address = address;
        this.userPsw = userPsw;
        this.picAddr = picAddr;
    }

    private int userId;
    private String userName;
    private String phoneNum;
    private String address;
    private String userPsw;
    private String picAddr;

    public int getUserId() { return userId; }
    public void setUserId(int userId) { this.userId = userId; }

    public String getUserName() { return userName; }
    public void setUserName(String userName) { this.userName = userName; }

    public String getPhoneNum() { return phoneNum; }
    public void setPhoneNum(String phoneNum) { this.phoneNum = phoneNum; }

    public String getAddress() { return address; }
    public void setAddress(String address) { this.address = address; }

    public String getUserPsw() { return userPsw; }
    public void setUserPsw(String userPsw) { this.userPsw = userPsw; }

    public String getPicAddr() { return picAddr; }
    public void setPicAddr(String picAddr) { this.picAddr = picAddr; }
}

LoginModel.java:對應最外層的 JSON 結構。注意 userInfo 這裡直接用上面抽好的類別承接,Gson 會自動遞迴解析。

package xxxxxx;

public class LoginModel {

    public LoginModel(boolean success, String message, int readNum,
                      int score, int contribution, UserInfo userInfo) {
        this.success = success;
        this.message = message;
        this.readNum = readNum;
        this.score = score;
        this.contribution = contribution;
        this.userInfo = userInfo;
    }

    private boolean success;
    private String message;
    private int readNum;
    private int score;
    private int contribution;
    private UserInfo userInfo;

    public boolean isSuccess() { return success; }
    public void setSuccess(boolean success) { this.success = success; }

    public String getMessage() { return message; }
    public void setMessage(String message) { this.message = message; }

    public int getReadNum() { return readNum; }
    public void setReadNum(int readNum) { this.readNum = readNum; }

    public int getScore() { return score; }
    public void setScore(int score) { this.score = score; }

    public int getContribution() { return contribution; }
    public void setContribution(int contribution) { this.contribution = contribution; }

    public UserInfo getUserInfo() { return userInfo; }
    public void setUserInfo(UserInfo userInfo) { this.userInfo = userInfo; }
}

LoginActivity.java:布局很簡單,兩個輸入框加一顆按鈕:

package xxxxx;

import xxxx; // 這裡import一堆套件的部分省略

public class LoginActivity extends Activity {

    EditText et_phone;
    EditText et_pwd;
    Button btn_login;

    public static String phone;
    String pwd;

    String url = xxxx; // 這是後端提供的接口網址
    public static LoginModel myModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        btn_login = (Button) findViewById(R.id.btn_login);
        et_phone = (EditText) findViewById(R.id.et_phone);
        et_pwd = (EditText) findViewById(R.id.et_pwd);

        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                phone = et_phone.getText().toString().trim();
                pwd = et_pwd.getText().toString().trim();
                loadData();
            }
        });
    }

    // 這就是透過接口取得資料庫資料的核心
    private void loadData() {
        RequestParams params = new RequestParams();
        // 參數名稱必須與接口文件完全一致
        params.addBodyParameter("phoneNum", phone);
        params.addBodyParameter("psw", pwd);

        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, url, params,
                new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Gson gson = new Gson();
                myModel = gson.fromJson(responseInfo.result, LoginModel.class);

                // 成功的話,跳轉到另一個畫面
                if (myModel.isSuccess()) {
                    Intent intent = new Intent(LoginActivity.this, BookCrossingMain.class);

                    // 把資料庫取回的資料透過 Intent 帶給下一頁
                    UserInfo myInfo = myModel.getUserInfo();
                    intent.putExtra("userId", myInfo.getUserId());
                    intent.putExtra("phoneNum", phone);
                    intent.putExtra("pwd", pwd);

                    startActivity(intent);
                    LoginActivity.this.finish();
                } else {
                    Toast.makeText(LoginActivity.this, myModel.getMessage(),
                            Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Toast.makeText(LoginActivity.this, "網絡出錯",
                        Toast.LENGTH_SHORT).show();
            }
        });
    }
}

情境二:接口回傳列表資料(以留言列表為例)

留言接口的請求參數:

伺服器回傳的結構:

這裡我把 model 與列表元素類別寫在同一個檔案中。BookCommentModel.java:

package xxxxxx;

import java.util.List;

public class BookCommentModel {

    public BookCommentModel(boolean success, String message, Object totalpages,
                            int currentpage, int totalrecords, int pagerows,
                            List<CommentLis> commentLis) {
        this.success = success;
        this.message = message;
        this.totalpages = totalpages;
        this.currentpage = currentpage;
        this.totalrecords = totalrecords;
        this.pagerows = pagerows;
        this.commentLis = commentLis;
    }

    private boolean success;
    private String message;
    private Object totalpages;
    private int currentpage;
    private int totalrecords;
    private int pagerows;
    private List<CommentLis> commentLis;

    public boolean isSuccess() { return success; }
    public void setSuccess(boolean success) { this.success = success; }

    public String getMessage() { return message; }
    public void setMessage(String message) { this.message = message; }

    public Object getTotalpages() { return totalpages; }
    public void setTotalpages(Object totalpages) { this.totalpages = totalpages; }

    public int getCurrentpage() { return currentpage; }
    public void setCurrentpage(int currentpage) { this.currentpage = currentpage; }

    public int getTotalrecords() { return totalrecords; }
    public void setTotalrecords(int totalrecords) { this.totalrecords = totalrecords; }

    public int getPagerows() { return pagerows; }
    public void setPagerows(int pagerows) { this.pagerows = pagerows; }

    public List<CommentLis> getCommentLis() { return commentLis; }
    public void setCommentLis(List<CommentLis> commentLis) { this.commentLis = commentLis; }

    /** 對應 JSON 陣列中的單一元素 */
    public static class CommentLis {
        private int commentId;
        private String bookId;
        private int userId;
        private String comment;
        private String commentTime;

        public int getCommentId() { return commentId; }
        public void setCommentId(int commentId) { this.commentId = commentId; }

        public String getBookId() { return bookId; }
        public void setBookId(String bookId) { this.bookId = bookId; }

        public int getUserId() { return userId; }
        public void setUserId(int userId) { this.userId = userId; }

        public String getComment() { return comment; }
        public void setComment(String comment) { this.comment = comment; }

        public String getCommentTime() { return commentTime; }
        public void setCommentTime(String commentTime) { this.commentTime = commentTime; }
    }
}

TabFragmentSecond.java:這裡是 Fragment,寫法與 Activity 幾乎相同。

單項布局 dynamic_list_item.xml:

Fragment 布局 fragment_tab_second 裡只有一個 ListView:

package xxxxxxx;

import xxxxx;

public class TabFragmentSecond extends Fragment {

    private ListView lv;
    BookCommentModel myModel;
    String url = URL_ADDR.DYNAMIN_URL;
    View v;

    // 頭像
    private int[] mImgs = {
        R.drawable.icon_book_head1, R.drawable.icon_book_head2, R.drawable.icon_book_head3,
        R.drawable.icon_book_head4, R.drawable.icon_book_head5, R.drawable.icon_book_head6
    };
    // 人名
    private int[] mNames = {1, 2, 3, 4};
    // 評論內容
    private String[] mOpinion = {"1111111", "2222222222222", "3333333333", "444444444"};

    private int count;          // 評論筆數
    private ListView mListView; // 評論列表

    private List<Map<String, Object>> list_data;
    private static final String DYNAMIC_PINGLUN = "評論 ";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.fragment_tab_second, container, false);
        init();
        return v;
    }

    private void init() {
        mListView = (ListView) v.findViewById(R.id.lv_dynamic);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id) {
                // 列表項目的點擊事件
            }
        });
        LoadData();
        InitData();
    }

    private void LoadData() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("userId", "888");
        params.addBodyParameter("pages", "1");
        params.addBodyParameter("num", "4");

        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, url, params,
                new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Gson gson = new Gson();
                BookCommentModel mComment =
                        gson.fromJson(responseInfo.result, BookCommentModel.class);

                if (mComment.isSuccess()) {
                    count = 4;
                    mNames = new int[count];
                    mOpinion = new String[count];
                    for (int i = 0; i < count; i++) {
                        mNames[i] = mComment.getCommentLis().get(i).getUserId();
                        mOpinion[i] = mComment.getCommentLis().get(i).getComment();
                    }
                    InitData();
                } else {
                    Log.i("comment user link", "fail");
                    InitData();
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Log.i("comment user onFailure", error.toString());
                InitData();
            }
        });
    }

    private void InitData() {
        list_data = new ArrayList<>();
        Map<String, Object> map_item;
        for (int i = 0; i < 4; i++) {
            map_item = new HashMap<>();
            map_item.put("image", mImgs[i]);
            map_item.put("title", mNames[i]);
            map_item.put("comment", mOpinion[i]);
            list_data.add(map_item);
        }

        SimpleAdapter simpleAdapter = new SimpleAdapter(
                getActivity(), list_data, R.layout.dynamic_list_item,
                new String[]{"image", "title", "comment"},
                new int[]{R.id.iv_dynamic_icon, R.id.iv_dynamic_title,
                          R.id.iv_dynamic_content});
        mListView.setAdapter(simpleAdapter);
    }
}

整套流程可以總結成三個要點:參數名稱必須與接口文件逐字對齊、JSON 的每一層結構都要有一個對應的 Java 類別、以及網路請求一定要放在非主執行緒。只要這三點掌握好,後端再怎麼改欄位,你也只要動 model 類別即可。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved