Inner AsyncTask不更新外部类中的成员变量

时间:2012-09-19 09:19:41

标签: android android-asynctask

我有一个应用程序,其中一个活动使用AsyncTask从另一个类中调用一个方法,该类连接到数据库以改变用户的登录凭据。 Activity EntryActivity有三个成员变量需要使用AsyncTask,carerID,firstName和surName的结果进行更新。当我第一次运行应用程序时,所有三个变量都为空,但如果我第二次按下登录按钮,变量设置正确,应用程序的行为应该如此。

在第一次运行应用程序时,有没有理由从onPostxecute中正确设置三个成员变量?

public class EntryActivity extends NfcBaseActivity{

    private LoginWebservice loginWebservice;
    private static final String TAG = EntryActivity.class.getSimpleName(); 
    private Button login;
    private EditText userName;
    private EditText passwordPin;
    NfcScannerApplication nfcscannerapplication;
    public static final String CUSTOM_QRCODE_ACTION = "com.carefreegroup.QRCODE_ACTION"; 
    private String carerID;
    private String firstName;
    private String surName;
    private boolean isValidated = false;


    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.entryscreen); 
        nfcscannerapplication = (NfcScannerApplication) getApplication();
        loginWebservice = new LoginWebservice(this);
        carerID = null;
        firstName = null;
        surName = null;




        userName = (EditText)findViewById(R.id.username);
        passwordPin = (EditText)findViewById(R.id.password);

        login = (Button)findViewById(R.id.buttonlogin);
        login.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                ////////////get user's input///////////


                String compId = "100";
                String theUsername = userName.getText().toString();
                String thePassword = passwordPin.getText().toString();
                String loginType = "1";



                String[] params = new String[]{compId, theUsername, thePassword, loginType};

                //validate user Asynchonously on background thread
                 new AsyncValidateCarer().execute(params);



                Log.e(TAG, "carerid =" + carerID + " firstname = " + firstName + " surnamee = " + surName);
                DateTime now = new DateTime();
                long loginTime = now.getMillis();
                String fullName = firstName +" " + surName;
                Log.e(TAG, "fullname = " + fullName); 

                if(carerID != null){

                ContentValues loginValues = new ContentValues();
                loginValues.putNull(LoginValidate.C_ID_INDEX);
                loginValues.put(LoginValidate.C_CARER_ID, carerID);
                loginValues.put(LoginValidate.C_COMP_ID, compId);
                loginValues.put(LoginValidate.C_CARER_NAME, fullName);
                loginValues.put(LoginValidate.C_PASSWORD, thePassword);
                loginValues.put(LoginValidate.C_DATE_TIME, loginTime);
                nfcscannerapplication.loginValidate.insertIntoCarer(loginValues);

                Toast.makeText(
                        EntryActivity.this,
                        "Carer logged in to System",
                        Toast.LENGTH_LONG).show();

                isValidated = true;

                Intent intent = new Intent(EntryActivity.this,
                        NfcscannerActivity.class);
                intent.setAction(CUSTOM_QRCODE_ACTION);
                startActivity(intent);


                }else{

                    Toast.makeText(
                            EntryActivity.this,
                            "Please check credentials",
                            Toast.LENGTH_LONG).show();

                }
                //////////////validate user/////////////////





            }
        });

        Button changeUser = (Button)findViewById(R.id.buttonchangeuser);
        changeUser.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Log.e(TAG, "change user button clicked");
                nfcscannerapplication.loginValidate.deleteTableCarer();
                Toast.makeText(
                        EntryActivity.this,
                        "Carer logged out",
                        Toast.LENGTH_LONG).show();
                EntryActivity.this.onCreate(savedInstanceState);
            }
        });


    }//end of onCreate

    private void hideSoftKeyboard() {

        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(passwordPin.getWindowToken(), 0);

    }

    private class AsyncValidateCarer extends AsyncTask<String, Void, ContentValues> {

        @Override
        protected ContentValues doInBackground(String... params) {

            ContentValues cv = null;

            try {
                Log.e(TAG, "inside asynctask");
                cv = loginWebservice.validateCarer(params[0], params[1], params[2], params[3]);
                 if (cv != null){
                     Log.e(TAG, "cv = not null!");
                 }

            } catch (Exception e) {
               e.printStackTrace();
            } 
            return cv;

        }

        @Override
        protected void onPostExecute(ContentValues result) {
            Log.e(TAG, "inside onpostexecute");

            EntryActivity.this.carerID = (String) result.get("carerID"); 
            EntryActivity.this.firstName = (String) result.get("firstname");
            EntryActivity.this.surName = (String) result.get("surname");
        }
    }

}

[更新]

private class AsyncValidateCarer extends AsyncTask<String, Void, Void> {

        @Override
        protected Void doInBackground(String... params) {

            ContentValues cv = null;

            try {
                Log.e(TAG, "inside doInBackground");
                cv = loginWebservice.validateCarer(params[0], params[1], params[2], params[3]);
                carerID = (String) cv.get("carerID"); 
                firstName = (String) cv.get("firstname");
                surName = (String) cv.get("surname");
                 if (cv != null){
                     Log.e(TAG, "cv = not null! and exiting doInBackground");
                 }

            } catch (Exception e) {
               e.printStackTrace();
            }
            return null; 


        }


    }

2 个答案:

答案 0 :(得分:1)

AsyncTask将异步执行,因此您无法保证在“执行”方法调用之后,该任务实际上已完成。我的建议是在“onPostExecute”方法中移动“执行”调用后的所有内容(或至少与这些字段相关的内容)。

第一次点击似乎不起作用,第二次点击的原因是,在第一次“登录”点击和第二次点击之间,你等待AsyncTask完成。因此,当您第二次单击时,您会看到第一次执行的结果。请在“onPostExecute”中添加一些“Log”信息,以了解发生了什么。

希望有所帮助:)

答案 1 :(得分:0)

carerID = null;
firstName = null;
surName = null;

onCreate()方法移除上述语句,因为它们已经初始化为默认值,因为它们位于Class Scope中并被称为Instance Variables.