Не удается обновить пользовательский интерфейс из обратного вызова AWS Cognito «ForgotPasswordHandler» - PullRequest
0 голосов
/ 05 апреля 2019

Я не могу обновить пользовательский интерфейс из обратного вызова AWS ForgotPasswordHandler.Метод onSuccess вызывается, когда я сбрасываю пароль, но код внутри этого блока не влияет.

Я использую AWS Cognito с моим Android-приложением для регистрации, модулей входа в систему.Для сброса пароля AWS предоставляет функцию обратного вызова ForgotPasswordHandler, пользователю необходимо предоставить электронную почту, чтобы получить код после отправки кода, пользователю необходимо ввести код подтверждения и новый пароль.Отправка кода подтверждения, проверка кода и установка нового пароля выполняется с помощью объекта ForgotPasswordContinuation.Когда я нажимаю «Получить код» и закрываю действие, чтобы прочитать код по электронной почте и вернуться к своей активности, состояние ForgotPasswordContinuation было потеряно, и я не смог отправить код подтверждения и новый пароль на сервер.Подход, который я использовал, когда я получаю код, вызывается функция getResetCode обратного вызова, и я сохраняю состояние ForgotPasswordContinuation через фоновый поток.Когда я снова открываю занятие, я возвращаю объект ForgotPasswordContinuation и отправляю новый проверочный код и пароль.Все работает и вызывается onSuccess обратного вызова, который гарантирует, что пароль был успешно изменен.Когда я пытаюсь вызвать finish() внутри этого onSuccess, это не оказывает никакого влияния, и деятельность не разрушается.Я поместил этот код для запуска в интерфейсе основного потока, обработчики, но не повезло.Как я могу заставить это работать?Я пытаюсь спрятать счетчик в обратном вызове и завершить действие, но это не дает результата.onSuccess вызывается наверняка, потому что когда я регистрируюсь, я вижу текст журнала в методе onSuccess.Также, не выходя из экрана получения кода, если я не закрою это действие и не прочту код подтверждения из своего браузера и не введу код и новый пароль, то onSuccess будет работать правильно.Проблема возникает только тогда, когда я пытаюсь выйти из действия, чтобы открыть gmail и прочитать код подтверждения, когда я вернусь, введите новый пароль и код и выполните, тогда будет вызван onSuccess, но код внутри него не оказывает никакого влияния, ни счетчикскрывается, а вызов finish() не работает.

    GifImageView rotateLoading;
    TextView tryagain;
    private ForgotPasswordContinuation resultContinuation;
    Context context = ForgotPasswordActivity.this;
    private LinearLayout getCodeLayout,confirmationLayout;
    TextView forgotPassText;
    BackgroundService myServiceObject;
    private boolean verified = false;

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            BackgroundService.LocalBinder localBinder = (BackgroundService.LocalBinder) service;
            myServiceObject = localBinder.getService();
        }
        @Override
        public void onServiceDisconnected(ComponentName arg0) {
        }
    };


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


        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_forgot_password);

        Intent intent = new Intent(context, BackgroundService.class);
        context.startService(intent);
        context.bindService(intent, connection, Context.BIND_AUTO_CREATE);


        tryagain = findViewById(R.id.tryagain);
        forgotPassText = findViewById(R.id.forgotPassText);
        getCodeLayout = findViewById(R.id.getCodeLayout);
        confirmationLayout = findViewById(R.id.confirmationLayout);
        rotateLoading = findViewById(R.id.rotateloading);

        tryagain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateVariable(context,"LaunchScreen","0");
                getCodeLayout.setVisibility(View.VISIBLE);
                confirmationLayout.setVisibility(View.GONE);
                forgotPassText.setText("Enter the email address associated with your account");
            }
        });

        if(getVariable(context,"LaunchScreen").equals("3")) {
            getCodeLayout.setVisibility(View.GONE);
            confirmationLayout.setVisibility(View.VISIBLE);
            forgotPassText.setText("Enter verification code and set new password");
        }else {
            getCodeLayout.setVisibility(View.VISIBLE);
            confirmationLayout.setVisibility(View.GONE);
            forgotPassText.setText("Email verification");
        }

        final EditText editTextUsername = findViewById(R.id.editTextUsername);

        if(!getVariable(context,"email").equals("0")){
            editTextUsername.setText(getVariable(context,"email"));
        }

        Button buttonGetCode = findViewById(R.id.buttonGetCode);
        buttonGetCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(getInputText(editTextUsername).isEmpty()){
                    Utils.showAlertMessage(context, "Please enter email");
                }else{
                    if(Utils.isEmailValid(String.valueOf(editTextUsername.getText()))){
                        rotateLoading.setVisibility(View.VISIBLE);

                        CognitoSettings cognitoSettings = new CognitoSettings(ForgotPasswordActivity.this);
                        CognitoUser thisUser = cognitoSettings.getUserPool().getUser(String.valueOf(editTextUsername.getText()));

                        updateVariable(context,"email",String.valueOf(editTextUsername.getText()));

                        Utils.showLog(ForgotPasswordActivity.this,"calling forgot password to get confirmation code....");

                        thisUser.forgotPasswordInBackground(callback);
                    }else {
                        Utils.showAlertMessage(context, "Please enter correct email");
                    }
                }
            }
        });


        final EditText editTextCode = findViewById(R.id.editTextCode);
        final EditText editTextNewPassword = findViewById(R.id.editTextNewPassword);

        Button buttonResetPassword = findViewById(R.id.buttonResetPassword);
        buttonResetPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(getInputText(editTextCode).isEmpty()|| getInputText(editTextNewPassword).isEmpty()){
                    Utils.showAlertMessage(context, "Please enter both verification code and new password");
                }else{
                    if(getInputText(editTextNewPassword).length()<6){
                        Utils.showAlertMessage(context, "Password must be at least 6 characters");
                    }else {
                        rotateLoading.setVisibility(View.VISIBLE);

                        Utils.showLog(ForgotPasswordActivity.this,"got code & password, setting continuation object....");

                        if(myServiceObject.getContinuationObject() !=null){
                            Log.e("Teeeeesssttt","myServiceObject.getContinuationObject() !=null");
                            resultContinuation = myServiceObject.getContinuationObject();
                        }

                        resultContinuation.setPassword(String.valueOf(editTextNewPassword.getText()));
                        resultContinuation.setVerificationCode(String.valueOf(editTextCode.getText()));

                        Utils.showLog(ForgotPasswordActivity.this,"got code & password, calling continueTask()....");

                        // Let the forgot password process continue
                        resultContinuation.continueTask();
                    }
                }
            }
        });
    }

    private ForgotPasswordHandler callback = new ForgotPasswordHandler() {
        @Override
        public void onSuccess() {
            /*Forgotten password process completed successfully
             new password has been successfully set*/
            Utils.showToast(ForgotPasswordActivity.this,"Password changed successfully");

            verified = true;


            Handler h = new Handler(context.getMainLooper());
            h.post(new Runnable() {
                @Override
                public void run() {
                    if(rotateLoading.getVisibility() == View.VISIBLE){
                        rotateLoading.setVisibility(View.GONE);
                    }
                }
            });

        }

        @Override
        public void getResetCode(ForgotPasswordContinuation continuation) {


            Utils.showLog(ForgotPasswordActivity.this,"in getResetCode....");

             /* A code will be sent
             , use the "continuation" object to continue with the forgot password process*/
            // This will indicate where the code was sent
            CognitoUserCodeDeliveryDetails codeSentHere = continuation.getParameters();

            Utils.showToast(ForgotPasswordActivity.this,"Code sent here: " + codeSentHere.getDestination()+". Don't forget to check SPAM folder");
            forgotPassText.setText("Enter verification code and set new password");
            // create field so we can use the continuation object in our reset password button
            resultContinuation = continuation;

            myServiceObject.setContinuationObject(continuation);

            getCodeLayout.setVisibility(View.GONE);
            confirmationLayout.setVisibility(View.VISIBLE);

            Handler h = new Handler(context.getMainLooper());
            h.post(new Runnable() {
                @Override
                public void run() {
                    if(rotateLoading.getVisibility() == View.VISIBLE){
                        rotateLoading.setVisibility(View.GONE);
                    }
                }
            });

        }

        public void onFailure(final Exception exception) {

            // Forgot password processing failed

            Handler h = new Handler(context.getMainLooper());
            h.post(new Runnable() {
                @Override
                public void run() {
                    if(rotateLoading.getVisibility() == View.VISIBLE){
                        rotateLoading.setVisibility(View.GONE);
                    }

                    String errorParts[] = exception.getMessage().split("\\(");
                    Utils.showAlertMessage(ForgotPasswordActivity.this,errorParts[0]);
                }
            });
        }
    };

    @Override
    protected void onStop() {
        super.onStop();

        Log.e("Txt","onStop");

        try {
            unbindService(connection);
        }catch (IllegalArgumentException e){
            e.printStackTrace();
        }

        if(confirmationLayout.getVisibility() == View.VISIBLE){
            if(verified){
                updateVariable(context,"LaunchScreen","0");
            }else {
                updateVariable(context,"LaunchScreen","3"); //  enter code and reset password
            }
        }else if(getCodeLayout.getVisibility() == View.VISIBLE) {
            // get code layout
            Intent mainIntent = new Intent(context,LoginActivity.class);
            startActivity(mainIntent);
        }
    }

onSuccess вызов метода Я хочу скрыть счетчик и завершить действие, но этот код не выполняется, он ничего не делает.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...