ASynctask的doInBackground()中return语句的目的是什么?

时间:2012-03-30 07:52:27

标签: android android-asynctask android-ui

如果我将return语句设置为0或1,我的登录系统的这个方面工作正常,但如果我使用null则失败。这全部改编自http://256design.com/blog/android-login-asynctask/,其中此特定返回看起来如下所示。

public LoginTask(Polling activity, ProgressDialog progressDialog)
    {
        this.activity = activity;
        this.progressDialog = progressDialog;
    }    

protected Integer doInBackground(String... arg0) {
            EditText userName = (EditText)activity.findViewById(R.id.emailEditText);
            EditText passwordEdit = (EditText)activity.findViewById(R.id.passEditText);


            String email = userName.getText().toString();
            String password = passwordEdit.getText().toString();
            UserFunctions userFunction = new UserFunctions();
            JSONObject json = userFunction.loginUser(email, password);
            progressDialog.dismiss();
            // check for login response
            //Log.v("test", Integer.toString(jsonParser.getResponseCode()));
            try {
                if (json.getString(KEY_SUCCESS) != null) {
                    //loginErrorMsg.setText("");
                    //loginFragment.loginErrorMsg.setText("Success");
                    String res = json.getString(KEY_SUCCESS);

                    if(Integer.parseInt(res) == 1){
                        //user successfully logged in
                        // Store user details in SQLite Database
                        DatabaseHandler db = new DatabaseHandler(activity.getApplicationContext());
                        JSONObject json_user = json.getJSONObject("user");
                        //Log.v("name", json_user.getString(KEY_NAME));
                        // Clear all previous data in database
                        userFunction.logoutUser(activity.getApplicationContext());
                        db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), 
                                json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));                        


                        // Close Login Screen
                        //finish();
                        //loginErrorMsg = (TextView)activity.findViewById(R.id.loginErrorMsg);
                        //loginErrorMsg.setText("logged in");
                        //passwordEdit.setText("");
                    }else{
                        // Error in login
                        //progressDialog.setMessage("Incorrect username or password");
                        //loginErrorMsg.setText("Incorrect username/password");
                    }

                }

            } catch (NullPointerException e) {
                e.printStackTrace();

            }
            catch (JSONException e) {
                e.printStackTrace();
            }

            return 1;
        }

我使用的教程,看一下responseCode:

protected Integer doInBackground(String... arg0) 
{
    String result = "";
    int responseCode = 0;
    try 
    {
        HttpClient client = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://www.256design.com/projectTransparency/project/headerLogin.php");

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("emailAddress", arg0[0]));
            nameValuePairs.add(new BasicNameValuePair("password", arg0[1]));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        int executeCount = 0;
        HttpResponse response;
        do
        {
            progressDialog.setMessage("Logging in.. ("+(executeCount+1)+"/5)");
            // Execute HTTP Post Request
            executeCount++;
            response = client.execute(httppost);
            responseCode = response.getStatusLine().getStatusCode();                        
            // If you want to see the response code, you can Log it
            // out here by calling:
            // Log.d("256 Design", "statusCode: " + responseCode)
        } while (executeCount < 5 && responseCode == 408);

        BufferedReader rd = new BufferedReader(new InputStreamReader(
                response.getEntity().getContent()));

        String line;
        while ((line = rd.readLine()) != null)
        {
            result = line.trim();
        }
        id = Integer.parseInt(result);
    }
    catch (Exception e) {
        responseCode = 408;
        e.printStackTrace();
    }
    return responseCode;
}

4 个答案:

答案 0 :(得分:2)

DoInBackground向postExecute方法返回值,并且传递null不验证条件:

if(headerCode == 202)
activity.login(id);

答案 1 :(得分:2)

目的是将作业的结果(在工作线程上执行)传递给onPostExecute,以便在UI线程上处理结果。如果要更新用户界面以响应成功的作业运行,则需要这样做。

答案 2 :(得分:1)

是您发送给postExecute的价值:

http://developer.android.com/reference/android/os/AsyncTask.html#onPostExecute(Result

  

protected void onPostExecute(结果结果)

     

之后在UI线程上运行   doInBackground(参数...)。

     

指定的结果是返回的值   通过doInBackground(Params ...)。

     

如果任务不会调用此方法   被取消了。

     

参数:   result 由doInBackground(Params ...)计算的操作结果。

答案 3 :(得分:1)

protected class InitTask extends AsyncTask<Context, Integer, Integer>

在上面的行中,我们定义了子类以及将传递给回调的三个参数。回调看起来像这样:

<强> doInBackground()

@Override
protected Integer doInBackground( Context... params )  {
     return super.doInBackground( params )
}

此方法中处理的任何内容都在sperate线程中处理。 请注意,返回值的数据类型是Integer,对应于类定义中的第三个类型参数。当此线程完成时,此方法返回的值将传递给onPostExecute()方法

如果您传递 null作为回报,那么它会失败方法onPostExecuted()上的条件

相关问题