0

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

在应用程序的第一次运行中没有从 onPostexecute 正确设置三个成员变量是否有原因?

.

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; 


        }


    }
4

2 回答 2

1

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

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

希望能帮助到你:)

于 2012-09-19T09:33:08.933 回答
0
carerID = null;
firstName = null;
surName = null;

从方法中删除上面的 there 语句onCreate(),因为它们已被初始化为它们的默认值,因为它们在Class Scope和 被称为Instance Variables.

于 2012-09-19T09:23:41.810 回答