0

I am able to run following code without any issue

EditText[] course_name = new EditText[4];
OnCreate {
        ConstraintLayout layout = findViewById(R.id.layout_setupclass);
        course_name[0] = new EditText(this);
        course_name[0] = (EditText) LayoutInflater.from(this).inflate(R.layout.edittext, null);
        layout.addView(course_name[0]);
}

But app would crash when I try this

EditText[] course_name = new EditText[4];
OnCreate {
        ConstraintLayout layout = findViewById(R.id.layout_setupclass);
        for(int i=0; i<5; i++)
        {
            course_name[i] = new EditText(this);
            course_name[i] = (EditText) LayoutInflater.from(this).inflate(R.layout.edittext, null);
            layout.addView(course_name[i]);
        }
}

1 Answer 1

1

you are creating array with 4 elements capacity new EditText[4];, but in your iteration you have 5 in-for-loop calls (i=0 to 4). index 4 doesn't exists in array (arrays are 0-based indexed), so you are getting ArrayIndexOutOfBoundsException on course_name[i] call (when i=4, as max may be 3 due to size of array)

btw. calling course_name[i] = new EditText(this); is redundant, as in very next line you are attaching another (inflated from XML) view to this variable

Sign up to request clarification or add additional context in comments.

2 Comments

Jeez that's so silly of me; spent almost half an hour over this! Thanks for pointing that out.
happens :) btw. post exception stactrace in comments, you can find it in Logcat tab in Android Studio. I bet this exception name would lead you to resolution without posting question here :) consider upvoting/accepting answer if helpful, good luck!

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.