Friday 17 January 2014

Adapters In Android



Adapters in Android are a bridge between the Adapter View (e.g. ListView) and the underlying data for that view. Imagine what would have been the world without adapter !.

Without Adapters, to implement the ListView functionality, you will need to:


  • Create a TextView within a ScrollView group.
  • Then you will have to implement pagination concept for the contents of the TextView.
  • You will also have to write additional code to identify the click event on a particular row in theTextView.

You may be asking why we need Pagination?

Imagine that you are creating an application that needs to display all your emails and the user will be able to scroll through them. I get around 100 emails on a daily basis and even if we consider 10 emails per day, the email data is going to be extremely huge. If you do not implement pagination, you will have major performance issues in retrieving all that data and showing it on the mobile screen. Thank God, we have adapters in Android and adapter views!

Below is a conceptual diagram which shows the high level working of the Android Adapter:







Let us now understand the internal working of an Android Adapter and how it acts as a data pump to the adapter view.


Adapters call the getView() method which returns a view for each item within the adapter view. The layout format and the corresponding data for an item within the adapter view is set in the getView() method. Now, it will be a performance nightmare if getView()returns a new View every time it is called. Creating a new view is very expensive in Android as you will need to loop through the view hierarchy (using the find ViewbyID ()method) and then inflate the view to finally display it on the screen.It also puts a lot of pressure on the garbage collector. That is because when the user is scrolling through the list, if a new view is created; the old view (since it is not recycled) is not referenced and becomes a candidate to be picked up by the garbage collector. So what Android does is that it recycles the views and reuses the view that goes out of focus.

Below is a visual representation of this recycle process:





In the above figure, let us assume we are displaying the months in a year in a ListView. To begin with, the months January till May are shown in the screen. When you scroll the view, the month January goes out of the display area of the mobile screen. As soon as the January view goes out of the screen, the Adapter View (ListView in this case) sends the view to something called a recycler.So when you scroll up, the getView () method is called to get the next view (which is June). This method getView()has a parameter called convertview which points to the unused view in the recycler. Through the convertview, the Adapter tries to get hold of the unused view and reuse it to display the new view (which is June in this case).


No comments:

Post a Comment