Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

Scott Junner
Scott Junner
9,010 Points

Dynamically adding items to a ListView (by user)

This is not a question! Instead it's a contribution.

After completing the Golf Scorecard project in Android Activity Lifecycle by Ben Deitch, I felt confident I could at least begin to tackle an app idea I've been keeping on the back burner until I understood some fundamental concepts about Lists and Adapters etc. etc.

The next fundamental problem I faced was how to allow a user to add an item to a list on the fly. Having figured it out I thought I would share my code so others could see how to do it too.

The crux of the process appears to be to create a custom ArrayAdapter https://developer.android.com/reference/android/widget/ArrayAdapter.html

and an ArrayList https://developer.android.com/reference/java/util/ArrayList.html

instead of a BaseAdapter with a standard array of your chosen data object.

As covered in the android Docs, ArrayList allows you to manipulate the size of the array, and has the arrayList.add() method so you can add an item to the list when the user clicks a button and then call adapter.notifyDataSetChanged() method to update the UI.

In the code provided here you will find the user can add a list item through an option in the options menu in the action bar. https://gist.github.com/HologramOfMe/16e03d1d3b291966177abd725a870865

Happy coding.

Ben Deitch
Ben Deitch
Treehouse Teacher

Cool stuff! Thanks for sharing :)