0

i am recreating a typing app for education purposes. The goal is to type the words of the paragraph. When a word is correct the word turns green, the editText field get cleared and its the next words turn. At the end every word is green and than the app crashs because the Activity is looking for the next word to turn green but doesn't find something.

Sample Picture

Do you have a idea how I can stop the "search" at the end? I thought about saying:

if ("written words" equals "words of the text that should be written")

than, end the focus on the editText field and show the score "Success" for example.

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_paragraph_game);


    paragraphTextView = findViewById(R.id.txtParagraph);
    edtInput = findViewById(R.id.edtTextWriter);
    timerView = findViewById(R.id.txtTimer);
    edtInput.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);


    //Sofortiger Fokus auf Textfeld
    edtInput.requestFocus();
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(edtInput, InputMethodManager.SHOW_IMPLICIT);

    try {
        refreshParagraph();
    } catch (IOException e) {
        e.printStackTrace();
    }
    setTitle(getString(R.string.paragraph_title));
    edtInput.addTextChangedListener(this);
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    //empty method
}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {


    //vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv//
    if (s.toString().replace(" ", "").equals(wordList.get(wordIndex))) {
        inputClean = true;
        numberOfLetters += s.length();
        wordIndex++;
    //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^//

        }

    }
}

@Override
public void afterTextChanged(Editable s) {
    if (inputClean) {
        inputClean = false;
        edtInput.setText("");




        updateColor(paragraphTextView, paragraphInitializer.getNextIndex(wordIndex - 1));
    } else if (!wordList.get(wordIndex).contains(s.toString().replace(" ", ""))) {
        undoColorChange(paragraphTextView, paragraphInitializer.getCurrentIndex(), paragraphInitializer.lookaheadIndex(wordIndex));
    }
}

protected void refreshParagraph() throws IOException {
    paragraphInitializer = new ParagraphInitializer(this);
    String paragraph = paragraphInitializer.getRandomParagraph();
    wordList = paragraphInitializer.getWords(paragraph);
    paragraphTextView.setText(paragraph, TextView.BufferType.SPANNABLE);
    inputClean = false;
    wordIndex = 0;
    numberOfWords = paragraphInitializer.getWordCount();
    countDownTimer = new CountDownTimer(Constants.MILLIS_IN_FUTURE, Constants.COUNTDOWN_INTERVAL) {
        @SuppressLint("SetTextI18n")
        @Override
        public void onTick(long millisUntilFinished) {
            timerView.setText("00:" + millisUntilFinished / 1000);
            if ((millisUntilFinished / 1000) < 16)
                timerView.setTextColor(Color.rgb(255, 34, 34));

        }

        @Override
        public void onFinish() {
            timerView.setText(getString(R.string.zero));
            edtInput.setEnabled(false);


            //initializeResultDialog();

            //pushFirebaseValues();


            //Intent intent = new Intent(ParagraphGameActivity.this, ResultParagraphActivity.class);
            //startActivity(intent);



        }
    }.start();
}

private void updateColor(TextView paragraphTextView, int nextIndex) {
    Spannable wordToSpan = new SpannableString(paragraphTextView.getText());
    //Neu einfärben in Grün
    wordToSpan.setSpan(new ForegroundColorSpan(Color.rgb(59, 226, 8)), 0, nextIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    paragraphTextView.setText(wordToSpan);


}

private void undoColorChange(TextView paragraphTextView, int currentIndex, int lookaheadIndex) {
    Spannable wordToSpan = new SpannableString(paragraphTextView.getText());
    //Neu einfärben falls Falsch
    wordToSpan.setSpan(new ForegroundColorSpan(Color.rgb(226, 8, 8)), currentIndex, lookaheadIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    paragraphTextView.setText(wordToSpan);
}


private void pushFirebaseValues() {
    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference(Constants.USER_SCORE);
    String userName = getSharedPreferences(Constants.USER_PREFERENCE, Context.MODE_PRIVATE).getString(Constants.USER_NICK, getString(R.string.OK));

    User user = new User(userName, numberOfLetters / 5, numberOfLetters, false);

    if (userName != null) {
        databaseReference.child(userName).setValue(user);
    } else {

        //DatabaseReference databaseReference1 = FirebaseDatabase.getInstance().getReference(Constants.USER_SCORE);
        Query query = databaseReference.orderByChild("score-list");
        query.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot resultsSnapshot) {
                for (DataSnapshot userSnapshot : resultsSnapshot.getChildren()) {
                    User user = new User(userName, numberOfLetters / 5, numberOfLetters, false);
                    userSnapshot.getRef().setValue(user);
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                throw databaseError.toException();
            }
        });


    }
}

}

the error occures in the highlighted line. It looks like this:

vvvvvvvvvv
this line
^^^^^^^^^^

Thanks for your help! :)

----------- here is the complete logcat --------------

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 21599
java.lang.IndexOutOfBoundsException: Index: 8, Size: 8
    at java.util.ArrayList.get(ArrayList.java:437)
    at com.example.myapplication.ParagraphGameActivity.onTextChanged(ParagraphGameActivity.java:76)
    at android.widget.TextView.sendOnTextChanged(TextView.java:11785)
    at android.widget.TextView.setText(TextView.java:6965)
    at android.widget.TextView.setText(TextView.java:6761)
    at android.widget.EditText.setText(EditText.java:145)
    at android.widget.TextView.setText(TextView.java:6713)
    at com.example.myapplication.ParagraphGameActivity.afterTextChanged(ParagraphGameActivity.java:88)
    at android.widget.TextView.sendAfterTextChanged(TextView.java:11816)
    at android.widget.TextView$ChangeWatcher.afterTextChanged(TextView.java:15266)
    at android.text.SpannableStringBuilder.sendAfterTextChanged(SpannableStringBuilder.java:1287)
    at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:587)
    at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:517)
    at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:38)
    at android.view.inputmethod.BaseInputConnection.replaceText(BaseInputConnection.java:867)
    at android.view.inputmethod.BaseInputConnection.commitText(BaseInputConnection.java:199)
    at com.android.internal.widget.EditableInputConnection.commitText(EditableInputConnection.java:177)
    at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:345)
    at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:93)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:246)
    at android.app.ActivityThread.main(ActivityThread.java:8512)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)

Greetings

Zimooon
  • 25
  • 3

0 Answers0