Android背景Web服务问题

时间:2014-05-23 11:11:44

标签: android android-asynctask

我真的需要你的帮助。我正在构建一个需要大量HTTP请求的Android应用程序,例如登录到服务器(检查用户是否存在)以及将会话存储到数据库(user_sessions表),添加,更新和删除记录。

在我的登录活动中,我有我的AsyncTask(检查用户是否退出)和其他后台线程(记录用户会话并将用户信息下载到数据库)。这很成功。接下来,当我更新用户信息时,它会成功更新。但是如果我使用我的网络应用更新怎么办?我应该在我的Android应用程序上显示最新更新的信息。我该如何解决这个问题?

这是我到目前为止所尝试的:

 private void logSessionToServer() {
    // TODO Auto-generated method stub

    Thread thread = new Thread(){
        public void run(){
            strUsername = etUsername.getText().toString();

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair( TAG_USERNAME, strUsername ));

            // getting JSON Object
            // Note it accepts POST method only
            JSONObject json = jsonParser.makeHttpRequest(url_log_session,
                "POST", params);

            // check log cat from response
            Log.d("Create Response", json.toString());

            // check for success tag
            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {

                    Log.d("", "Successfully logged session!");


                } else {
                    // failed 
                    Log.d("", "Not Successful!");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    };

    thread.start();

}

/**
 * Background Async Task to Create new record
 * */
class LoginTask extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Login.this);
        pDialog.setIcon(R.drawable.upload);
        pDialog.setTitle("Connecting to server");
        pDialog.setMessage("Validating login details..");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    /**
     * 
     * */
    protected String doInBackground(String... args) {

        strUsername = etUsername.getText().toString();
        strPassword = etPassword.getText().toString();

        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair( TAG_USERNAME, strUsername ));
        params.add(new BasicNameValuePair( TAG_PASSWORD, strPassword ));

        // getting JSON Object
        // Note it accepts POST method only
        JSONObject json = jsonParser.makeHttpRequest(url_login,
            "POST", params);


        // check log cat from response
        Log.d("Create Response", json.toString());

        // check for success tag
        try {
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {

                logSessionToServer(); // Save login to server

                saveUserInfoToDB(); // Save user info to DB

                saveUserloggedIn(); // Save user logged in to preference

                savePriestInfoToDB(); // Save priest to DB

                Log.d("", "Successful Login!");

                Intent i = new Intent(Login.this, MainActivity.class);
                startActivity(i);
                finish();
            } else {
                // failed 

                new Thread()
                {
                    public void run()
                    {
                        runOnUiThread(new Runnable()
                        {
                            public void run()
                            {
                                Toast.makeText(getBaseContext(), 
                                        "Not Successful Login", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                }.start();

                Log.d("", "Not Successful Login!");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;


    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String result) {
        // dismiss the dialog once done
        pDialog.dismiss();
    }

}

private void saveUserInfoToDB() {
    // TODO Auto-generated method stub


    Thread thread = new Thread(){
        public void run(){

            // Create the array 
            arraylist = new ArrayList<HashMap<String, String>>();
            // Retrieve JSON Objects from the given website URL in JSONfunctions.class
            String result = JSONFunctions.getJSONfromURL(url_view_loggedUser_profile);

            try {
                JSONArray jr = new JSONArray(result);
                for(int i=0;i<jr.length();i++)
                 {  
                          HashMap<String, String> map = new HashMap<String, String>();
                          jb = (JSONObject)jr.get(i);
                          map.put(TAG_FIRSTNAME, jb.getString(TAG_FIRSTNAME));
                          map.put(TAG_MIDDLENAME, jb.getString(TAG_MIDDLENAME));
                          map.put(TAG_LASTNAME, jb.getString(TAG_LASTNAME));
                          map.put(TAG_EMAIL, jb.getString(TAG_EMAIL));
                          map.put(TAG_AGE, jb.getString(TAG_AGE));
                          map.put(TAG_GENDER, jb.getString(TAG_GENDER));
                          map.put(TAG_USERNAME, jb.getString(TAG_USERNAME));
                          map.put(TAG_PASSWORD, jb.getString(TAG_PASSWORD));
                          map.put(TAG_BARANGAY, jb.getString(TAG_BARANGAY));
                          map.put(TAG_COMPLETEADDRESS, jb.getString(TAG_COMPLETEADDRESS));
                          map.put(TAG_CUS_ID, jb.getString(TAG_CUS_ID));
                          map.put(TAG_REG_DATE, jb.getString(TAG_REG_DATE));
                          map.put(TAG_BD_MONTH, jb.getString(TAG_BD_MONTH));
                          map.put(TAG_BD_DATE, jb.getString(TAG_BD_DATE));
                          map.put(TAG_BD_YEAR, jb.getString(TAG_BD_YEAR));
                          arraylist.add(map);

                          String strCusID = jb.getString(TAG_CUS_ID);
                          String strFname = jb.getString(TAG_FIRSTNAME);
                          String strMname = jb.getString(TAG_MIDDLENAME);
                          String strLname = jb.getString(TAG_LASTNAME);
                          String strEmail = jb.getString(TAG_EMAIL);
                          String strAge = jb.getString(TAG_AGE);
                          String strGender = jb.getString(TAG_GENDER);
                          String strUsername = jb.getString(TAG_USERNAME);
                          String strPassword = jb.getString(TAG_PASSWORD);
                          String strBarangay = jb.getString(TAG_BARANGAY);
                          String strCompleteAddress = jb.getString(TAG_COMPLETEADDRESS);
                          String strRegDate = jb.getString(TAG_REG_DATE);
                          String strBDMonth = jb.getString(TAG_BD_MONTH);
                          String strBDDate = jb.getString(TAG_BD_DATE);
                          String strBDYear = jb.getString(TAG_BD_YEAR);

                          try{



                              dbHelper.insertEntry(strCusID, strFname, strMname, strLname, strEmail, 
                                      strAge, strGender, strUsername, strPassword, 
                                      strBarangay, strCompleteAddress, strRegDate, 
                                      strBDMonth, strBDDate, strBDYear);
                              Log.d("Response", "Successfully inserted record");


                          } catch (SQLiteException e) {
                              Log.d("Response", "Not successful");
                          }

                 }
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }

        }
    };

    thread.start();

}

private void savePriestInfoToDB() {
    // TODO Auto-generated method stub


    Thread thread = new Thread(){
        public void run(){

            // Create the array 
            arraylist = new ArrayList<HashMap<String, String>>();
            // Retrieve JSON Objects from the given website URL in JSONfunctions.class
            String result = JSONFunctions.getJSONfromURL(URL_VIEW_PRIESTS);

            try {
                JSONArray jr = new JSONArray(result);
                for(int i=0;i<jr.length();i++)
                 {  
                          HashMap<String, String> map = new HashMap<String, String>();
                          jb = (JSONObject)jr.get(i);
                          map.put(TAG_P_ID, jb.getString(TAG_P_ID));
                          map.put(TAG_P_FIRSTNAME, jb.getString(TAG_P_FIRSTNAME));
                          map.put(TAG_P_MIDDLENAME, jb.getString(TAG_P_MIDDLENAME));
                          map.put(TAG_P_LASTNAME, jb.getString(TAG_P_LASTNAME));
                          map.put(TAG_P_EMAIL, jb.getString(TAG_P_EMAIL));
                          map.put(TAG_P_AGE, jb.getString(TAG_P_AGE));
                          map.put(TAG_P_ADDRESS, jb.getString(TAG_P_ADDRESS));
                          map.put(TAG_P_CONTACT, jb.getString(TAG_P_CONTACT));
                          map.put(TAG_P_STATUS, jb.getString(TAG_P_STATUS));
                          arraylist.add(map);

                          String strP_ID = jb.getString(TAG_P_ID);
                          String strP_Fname = jb.getString(TAG_P_FIRSTNAME);
                          String strP_Mname = jb.getString(TAG_P_MIDDLENAME);
                          String strP_Lname = jb.getString(TAG_P_LASTNAME);
                          String strP_Email = jb.getString(TAG_P_EMAIL);
                          String strP_Age = jb.getString(TAG_P_AGE);
                          String strP_Address = jb.getString(TAG_P_ADDRESS);
                          String strP_Status = jb.getString(TAG_P_STATUS);
                          String strP_Contact = jb.getString(TAG_P_CONTACT);

                          try{


                              dbHelper.insertPriest(strP_ID, strP_Fname, strP_Mname, 
                                      strP_Lname, strP_Email, strP_Age, 
                                      strP_Address, strP_Status, strP_Contact);
                              Log.d("Response - Priest", "Successfully inserted record");


                          } catch (SQLiteException e) {
                              Log.d("Response - Priest", "Not successful");
                          }

                 }
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }

        }
    };

    thread.start();

}

如果这是HTTP请求的最佳做法,请随时查看我的代码并提供反馈。我是Web Services的新手,所以我真的需要你的帮助。任何帮助将不胜感激。感谢

1 个答案:

答案 0 :(得分:0)

我刚才说的是:你写了一个每5秒下载一次用户信息的帖子。然后它会将下载的用户信息与您设备上已存储的用户信息进行比较。如果存在差异,则会进行更新,并且您的线程会调用更新的用户信息的新下载。