0

I am trying to make an app where you get the input trough the editText component and put it in the string like below:

number = findViewById(R.id.editText2); newNumber = number.getText().toString();

Now what I want is to replace the string start if a certain condition is met like this:

                if (number.getText().toString().substring(0, 1).equals("0")) {

                    newNumber = newNumber.replaceFirst("06", "3876");

                        Log.d("TAG", newNumber);
}

I get an error saying that the StringIndexIsOutOfBounds index=2 length=0

I also tried it like this:

 if (newNumber.startsWith("06")) {
                    newNumber = newNumber.replaceFirst("06", "3876");

                        Log.d("TAG", newNumber);
                        //Toast.makeText(MainActivity.this, newNumber, Toast.LENGTH_SHORT).show();
                    }
    else {
...
}

I get the else statement when I run this query.

Since I tried this in many combinations, a similar one produces an empty toast. (Can't remember what exactly did it, but it doesn't even matter as it is also not right)

What is wrong in my code? The string is all numbers, but I found it easiest to do the replacements on a string, if you know of a better implementation, be my guest. The input should be 9 numbers, and output should be 11 numbers (I am replacing 06 with 3876 so I get the 2 extra numbers there).

(I have searched SO for similar problems and some attempts were recreations, but none successful)

2 Answers 2

1

Ok, first of all, are u sure, you've the right string f.ex. 06xxxxxx in your var and is not empty?

Check your string

!number.getText().toString().isEmpty()

than try this:

EditText number = (EditText) findViewById(R.id.editText2);
String newNumber = number.getText().toString();

f(!number.getText().toString().isEmpty()){
        Log.d("TAG", newNumber);
        newNumber = newNumber.replaceFirst("06", "3876");
        Log.d("TAG", newNumber);
}
Sign up to request clarification or add additional context in comments.

1 Comment

The whole problem was that I defined my EditText and String in onCreate and not the onClick method. As soon as I did it that way, it was solved. Thanks Joschy and @piotr.wittchen
1

If you get StringIndexIsOutOfBounds index=2 length=0, it means that your TextView doesn't have any value predefined or provided by the user.

To avoid this error, you should verify if String is not empty like that:

if (!number.getText().toString().isEmpty() 
    && number.getText().toString().substring(0, 1).equals("0")) {
    // your code goes here...
}

Please remember, this condition won't be fulfilled as long as TextView is empty.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.