Passing Reference vs Value, 58 of 100 Days of…
I thought rebuilding the app would get things rolling. Turns out I was the one in my own way.
I removed an assignment statement which assigned the static original_adapter ArrayAdapter object to the dynamic display_adapter ArrayAdapter object.
You can find a video at the bottom of the page and a link to the source code here.
The assignment operator assigns references of objects. Since both adapters are objects, using the assignment operator assigns the reference of the original_adapter to the display_adapter. (click below)
This applied any changes made to the display_adapter object to the original_adapter.
The dynamic_adapter is meant to copy the original_adapter and is emptied prior to any updates based on the user’s input. The onEditorAction method clears the dynamic_adapter when the user presses enter on the keyboard.
Because it shares a reference with the original_adapter variable, pressing enter clears the original_adapter as well. As a result, any attempt to obtain specific indexes led to an ArrayOutOfBoundsException.
I will I replace this assignment with a for loop which adds each item of the original_adapter to the display_adapter. Using a for loop avoids assigning the reference and ensures the display_adapter can be updated independent of the original_adapter.
For more on this, watch the YouTube video below. For the source code click here. To read more about these exceptions, check out the Oracle documentation here
Join the mailing list to see updates like this every week!
Coding Fanatic
Image by Keith Johnston from Pixabay