美文网首页
践行代码整洁后的Java代码

践行代码整洁后的Java代码

作者: d61f25068828 | 来源:发表于2019-02-21 17:59 被阅读3次
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;

    }

}

相关文章

  • 践行代码整洁后的Java代码

  • [代码整洁之道]-整洁代码

    前段时间,看了代码整洁之道,顺手做了些笔记,分享给大家,和大家一起探讨整洁代码之道。 1.1要有代码 代码是我们最...

  • 学习,学习!!!

    确定工作后,看看以下三本书,并把jdk的源码吃透 《Effective Java》《代码整洁之道》《Java编程思...

  • 写出强而有力的代码

    导师推荐的几本书: 《Effective java》 《代码整洁之道》 《重构,改善既有代码的设计》 Effect...

  • 代码整洁

    1.整洁的代码 “破窗理论”:窗户破损了的建筑让人觉着似乎没人照管,于是别人也不再关心。他们放任窗户继续破损,最终...

  • 整洁代码

    一、代码的命名 1.变量名、方法名:小驼峰法(除第一个单词之外,其他单词首字母大写) 2.类名:大驼峰法 (所有单...

  • 代码整洁案列

    最近在看《代码整洁之道》这本书,受益颇多,发现了自己存在的好多问题,刚好这几天在做一道习题,结合书上所讲内容,对代...

  • 日更32/100(代码简洁之道)

    第一章 整洁的代码 主要讲了什么是整洁的代码,为什么要整洁的代码?不整洁有什么坏处,整洁有什么好处? 糟糕的代码 ...

  • 书写规范整洁的Java代码

    “Talk is cheap. Show me the code”相信百分之九十的程序员都听过,如果说有比这句更流...

  • 整洁的代码

    为什么写糟糕的代码? 1、不耐烦再搞这套程序,希望早点结束; 2、自己承诺要做其它事,要赶紧把手上的东西弄完好接着...

网友评论

      本文标题:践行代码整洁后的Java代码

      本文链接:https://www.haomeiwen.com/subject/faedyqtx.html