View Recycling in Android with ListView

Memory management is a crucial aspect of app development. Since mobile devices have very limited memory, it is necessary to use it carefully in our applications. One of the best practices involved in doing so is “view recycling“.

This article is about view recycling in Android and then a simple app is created which implements the practice of view recycling using ListView and ArrayAdapter in conjunction.

Need for View Recycling in Android
It is a practice to use as little memory as possible by recycling unused views to display new content instead of creating new views for the same. Suppose, we are scrolling down through a list of one thousand words. If we create a TextView for each word, we would need one thousand TextViews for this. This would waste a lot of memory since our device’s screen displays only 7-8 TextViews at a time and we need to scroll down if we want to see the rest of them.

When we scroll down, the TextViews which are at the top are not visible anymore. So, an inference can be taken that the top TextViews are not used by the user when they scroll down the ListView. Hence, unused TextViews are recycled and are used at the bottom when the user scrolls down. This way, instead of having one thousand TextViews, our task can be achieved with a few of them only.

Example for View Recycling in Android
One of the most common example is our mobile’s phone-book. We can have many contacts on our phone but instead of creating a new TextViews for each contact, our phone just recycles the unused scrolled up/down views and fills them with the new contact information and displays it again when the user scrolls up/down.

Implementation of View Recycling using ArrayAdapter and Listview

  • ArrayAdapter is a Java public class which extends from BaseAdapter class. An ArrayAdapter object makes the data (which is to be displayed) adapt to an array. Basically adapter is a bridge between UI component and data that helps to fill data in the UI component.
  • ListView is a Java public class which extends from AbsListView. ListView is a view which groups several items and displays them in a vertical list. This list is also automatically made scrollable if the amount of data supplied cannot be accommodated on the screen.
  • ArrayAdapter and ListView are required for view recycling. ListView asks for views from ArrayAdpapter by sending it a request and a specified position. ArrayAdpapter then returns the view at the specified position as the ListView keeps on asking for it until the device’s screen is filled. Now, when the user scrolls down, ListView gives ArrayAdpapter the top views which aren’t displayed on the device’s screen anymore. The ArrayAdpapter then erases the previous data of that ScrapView and sets new data and returns it to the ListView instead of creating a new view!

Below is a simple app to demonstrate this practice of memory management.