践行代码整洁后的Java代码

2019-02-21  本文已影响3人  d61f25068828
package com.bignerdranch.android.geoquiz;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.util.HashMap;


@SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")

public class QuizActivity extends AppCompatActivity {

    private static final String TAG = "QuizActivity";
    private static final String KEY_INDEX = "index";
    private static final String QUESTION_BANK = "question_bank";

    private static final int REQUEST_CODE_CHEAT = 0;
    private static final String DATA_WITH_QUESTION_BANK = "data_with_question_bank";
    private static final String CURRENT_INDEX = "current_index";

    public int getCurrentIndex() {
        Log.d("MyDeBug", "IN->getCurrentIndex():"+(Integer) mDataWithQuestionBank.get(CURRENT_INDEX));
        int currentIndex =  (Integer) mDataWithQuestionBank.get(CURRENT_INDEX);
        return currentIndex;
    }

    public void setCurrentIndex(int currentIndex) {
        mDataWithQuestionBank.put(CURRENT_INDEX, currentIndex);
        Log.d("MyDeBug", "IN->setCurrentIndex():"+(Integer) mDataWithQuestionBank.get(CURRENT_INDEX));
    }

    private View mTrueButton, mFalseButton;
    private View mNextButton, mBackButton;
    private View mCheatButton;

    private TextView mQuestionTextView;
    private TextView mStateTextView;
    private TextView mCheaterTextView;
    private TextView mAPILevelTextView;

    private Question[] mQuestionBank = new Question[]{
            new Question(R.string.question_australia, true),
            new Question(R.string.question_oceans, true),
            new Question(R.string.question_mideast, false),
            new Question(R.string.question_africa, false),
            new Question(R.string.question_americas, true),
            new Question(R.string.question_asia, true)
    };



    HashMap mDataWithQuestionBank = new HashMap();

    public static final String CHEAT_COUNTER = "cheatCounter";

    {
        final int INIT_VALUE = 0;
        mDataWithQuestionBank.put(CHEAT_COUNTER, INIT_VALUE);
        mDataWithQuestionBank.put(CURRENT_INDEX, INIT_VALUE);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quiz);

        findView();

        reloadInstanceState(savedInstanceState);

        updateView();

        setListener();

    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);
        savedInstanceState.putSerializable(QUESTION_BANK, mQuestionBank);
        savedInstanceState.putSerializable(DATA_WITH_QUESTION_BANK, mDataWithQuestionBank);
        return;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switchBaseOnActivityRequestCode(requestCode, data);
        return;

    }


    View.OnClickListener mPressPreviousButton = (v) -> {
        toPreviousIndexAndHandleExceptions();
        updateView();
        return;
    };

    private void toPreviousIndexAndHandleExceptions() {
        try {
            toPreviousQuestionBankIndex();
        } catch (ArrayIndexOutOfBoundsException exception) {
            showToast(R.string.first_question);
        }
    }

    private void toPreviousQuestionBankIndex() {
        if (getCurrentIndex() < 1) {
            throw new ArrayIndexOutOfBoundsException();
        } else {
            setCurrentIndex(getCurrentIndex()-1);;
        }
        return;
    }


    View.OnClickListener mPressNextButton = (v) -> {
        toNextIndexAndHandleExceptions();
        updateView();
        return;
    };

    private void toNextIndexAndHandleExceptions() {
        try {
            toNextQuestionBankIndex();
        } catch (ArrayIndexOutOfBoundsException exception) {
            showToast(R.string.last_question);
        }
    }

    private void toNextQuestionBankIndex() {
        if (getCurrentIndex() >= mQuestionBank.length - 1) {
            throw new ArrayIndexOutOfBoundsException();
        } else {
            setCurrentIndex(getCurrentIndex()+1);
        }
        return;
    }

    View.OnClickListener mPressCheatButton = (v) -> {
        if(canUserCheat()){

            startCheatActivityWithAnswer();
        }
        else{
            showToast(R.string.cheating_too_much);
            updateStateOfCheatButton();
        }
        return;
    };

    private void addToCheatCounter() {
        mDataWithQuestionBank.put(CHEAT_COUNTER, getNumberOfCheatCounter()+1);
    }

    private boolean canUserCheat() {
        boolean canUserCheat = getNumberOfCheatCounter()<=2;
        return canUserCheat;
    }

    private int getNumberOfCheatCounter() {
      int numberOfCheatCounter =  (Integer) mDataWithQuestionBank.get(CHEAT_COUNTER);
        return numberOfCheatCounter;
    }


    private void startCheatActivityWithAnswer() {
        boolean currentStandardAnswer = getCurrentQuestion().isStandardAnswer();
        Intent startCheatActivity = CheatActivity.newIntentToStartCheatActivityWithAnswer
                (QuizActivity.this, currentStandardAnswer);
        startActivityForResult(startCheatActivity, REQUEST_CODE_CHEAT);
        return;
    }


    private void setListener() {
        mTrueButton.setOnClickListener(mPressTrueButton);
        mFalseButton.setOnClickListener(mPressFalseButton);
        mNextButton.setOnClickListener(mPressNextButton);
        mBackButton.setOnClickListener(mPressPreviousButton);
        mCheatButton.setOnClickListener(mPressCheatButton);
    }


    private void findView() {
        findButton();
        findTextView();
    }

    private void findButton() {
        mTrueButton = findViewById(R.id.true_button);
        mFalseButton = findViewById(R.id.false_button);
        mNextButton = findViewById(R.id.next_button);
        mBackButton = findViewById(R.id.back_button);
        mCheatButton = findViewById(R.id.cheat_button);
    }


    private void findTextView() {
        mStateTextView = (TextView) findViewById(R.id.state_text_view);
        mQuestionTextView = (TextView) findViewById(R.id.question_text_view);
        mCheaterTextView = (TextView) findViewById(R.id.ischeater_text_view);
        mAPILevelTextView = (TextView) findViewById(R.id.api_level_text_view);
    }

    private void reloadInstanceState(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            mQuestionBank = (Question[]) savedInstanceState.getSerializable(QUESTION_BANK);
            mDataWithQuestionBank = (HashMap) savedInstanceState.getSerializable(DATA_WITH_QUESTION_BANK);
        } else {
            return;
        }

    }


    private void updateView() {
        updateStateOfButton();

        updateTextView();
    }

    private void updateStateOfButton() {
        updateStateOfTrueAndFalseButton();
        updateStateOfCheatButton();

    }

    private void updateStateOfCheatButton() {
        boolean theButtonState = canUserCheat();
        mCheatButton.setEnabled(theButtonState);
        return;
    }

    private void updateTextView() {
        updateTextViewOfIsQuestionFinished();
        updateTextViewOfQuestionText();
        updateTextViewOfIsTheUserACheater();
        updateTextViewOfApiLevel();

    }

    private void updateTextViewOfApiLevel() {
        final String DEVICE_OF_USER_API_LEVEL = "API Level " + Build.VERSION.SDK_INT;
        mAPILevelTextView.setText(DEVICE_OF_USER_API_LEVEL);
    }


    public void showToastForIsAnswerOfUserCorrect() {
        if (getCurrentQuestion().isAnswerOfUserCorrect()) {
            showToast(R.string.correct_toast);
        } else {
            showToast(R.string.Incorrect_toast);
        }
        return;

    }

    View.OnClickListener mPressTrueButton = new OnUserAnswered() {
        @Override
        public void onClick(View view) {
            storeUserAnswerIsTrue();
            super.onClick(view);
        }
    };

    View.OnClickListener mPressFalseButton = new OnUserAnswered() {
        @Override
        public void onClick(View view) {
            storeUserAnswerIsFalse();
            super.onClick(view);
        }
    };

    class OnUserAnswered implements View.OnClickListener {

        @Override
        public void onClick(View view) {
            showToastForIsAnswerOfUserCorrect();

            storeTheQuestionIsFinished();
            updateTextViewOfIsQuestionFinished();

            storeButtonIsUnable();
            updateStateOfTrueAndFalseButton();

        }
    }
    private void storeButtonIsEnable() {
        getCurrentQuestion().setButtonEnable(true);
    }

    private void storeButtonIsUnable() {
        getCurrentQuestion().setButtonEnable(false);
    }

    private void storeTheQuestionIsFinished() {
        getCurrentQuestion().setFinished(true);
    }

    private void storeUserAnswerIsTrue() {
        getCurrentQuestion().setUserAnswer(true);
    }

    private void storeUserAnswerIsFalse() {
        getCurrentQuestion().setUserAnswer(false);
    }

    private Question getCurrentQuestion() {

        Question question = mQuestionBank[getCurrentIndex()];
        return question;

    }


    private void showToast(int textStringResID) {

        Toast.makeText(QuizActivity.this,
                textStringResID,
                Toast.LENGTH_SHORT).show();

        return;
    }

    private void showToast(CharSequence textString) {

        Toast.makeText(QuizActivity.this,
                textString,
                Toast.LENGTH_SHORT).show();

        return;
    }

    private void updateTextViewOfQuestionText() {
        int question = getCurrentQuestion().getQuestionTextResId();
        mQuestionTextView.setText(question);
        return;
    }

    private void updateTextViewOfIsTheUserACheater() {
        if (getCurrentQuestion().isCheater()) {
            mCheaterTextView.setText(R.string.ischeater);
        } else {
            mCheaterTextView.setText(R.string.empty);
        }
        return;
    }


    private void updateTextViewOfIsQuestionFinished() {
        int stateTextView = getIsQuestionFinishedRsId();
        assert mStateTextView != null : "mStateTextView is null";
        mStateTextView.setText(stateTextView);
        return;
    }

    private int getIsQuestionFinishedRsId() {
        if (getCurrentQuestion().isFinished()) {
            return R.string.state_finished;
        }
        else{
            return R.string.state_unfinished;
        }

    }

    private void updateStateOfTrueAndFalseButton() {
        boolean theButtonState = getCurrentQuestion().isButtonEnable();

        mTrueButton.setEnabled(theButtonState);
        mFalseButton.setEnabled(theButtonState);
        return;
    }

    private void switchBaseOnActivityRequestCode(int requestCode, Intent data) {
        switch (requestCode) {
            case (REQUEST_CODE_CHEAT):
                if (parseCheatedData(data)) {
                    addToCheatCounter();
                    storeUserOfTheQuestionIsCheater();
                    updateTextViewOfIsTheUserACheater();
                    updateStateOfCheatButton();
                    showWarnToCheater(data);
                }
                return;
        }
        return;
    }


    private void storeUserOfTheQuestionIsCheater() {
        if (getCurrentQuestion().isCheater()) {
            return;
        } else {
            getCurrentQuestion().setCheater(true);
        }

        return;
    }

    private void showWarnToCheater(Intent data) {
        boolean cheated = parseCheatedData(data);
        showToast(String.valueOf(cheated));
        return;
    }

    private boolean parseCheatedData(Intent data) {
        boolean cheated
                = data.getBooleanExtra(CheatActivity.getExtraAnswerIsCheated(), false);
        return cheated;

    }

}
上一篇 下一篇

猜你喜欢

热点阅读