这次会把所有之前学过的东西应用在一起,写一个登入的功能。
1. Activity调用CONFIG,获得URL后
2. Activity再调用Okhttp,从服务器返回JSON
3. Activity调用GsonTools,把JSON转换成<List>DTO
4. Activity调用DAO的get、set方法,把叁数<List>DTO传到方法
5. DAO继承DbHelper,把<List>DTO储存到Sqlite
以下是部份代码的精要
1. Activity初始化GsonTools、OkHttp、DAO。
private OkHttp okhttp; private GsonTools gsonTools; private BitMap bitMap; private UserDAO userDAO; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); supportRequestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_login); okhttp = OkHttp.getInstance(); gsonTools = GsonTools.getInstance(); bitMap = BitMap.getInstance(); userDAO = new UserDAO(this); initUI(); isHavingUserInSqlite(); }
2. 必须在新线程下调用Okhttp,而在该线程下想刷新UI,必须用runOnUiThread()。
// Network thread new Thread(new Runnable() { @Override public void run() { // run your code here // UI Thread LoginActivity.this.runOnUiThread(new Runnable() { public void run() { // ui } }); } }).start();
3. 最核心的业务都在这里。
private void validUser() { // Network thread new Thread(new Runnable() { @Override public void run() { ResultDTO resultDTO; // check weather user is exist? userExistURL = Configuration.isUserExistURL(userName, userPassword); userExistResult = okhttp.getResponse(userExistURL); resultDTO = gsonTools.getLogin(userExistResult); // get user info if user is exist if ( resultDTO.getResult().equals("1") ) { userGetURL = Configuration.getUserURL(resultDTO.getId()); userResult = okhttp.getResponse(userGetURL); userDTO = gsonTools.getUser(userResult); // save user info into SQlite if ( userDAO.setUser(userDTO) ) { intent = new Intent(LoginActivity.this, MainActivity.class); startActivity(intent); } } else { loginMsg = "密碼或帳號不正確"; } // UI Thread LoginActivity.this.runOnUiThread(new Runnable() { public void run() { tvLoginResult.setText(loginMsg); } }); } }).start(); }