Adapters

Adapters in android are a bridge between the adapter view and the underlying data for that view.

How adapter works in Android?

adapters.png

1.Adapter call the getView() method which returns a view for each item within the adapter view.
2.Creating a new view is very expensive in Android
3.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 . So what Android does is that it recycles the views and reuses the view that goes out of focus.

Example ?

adapters1

1.In the above figure, let us assume we are displaying the months in a year in a ListView.
2.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.
3.As soon as the January view goes out of the screen, the Adapter View sends the view to something called a recycler.
4.So when you scroll up, the getView () method is called to get the next view (which is June).
5.This method getView() has a parameter called convertview which points to the unused view in the recycler.
6.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).

Code Example ?

@Override
publicView getView(intitempos, View convertView, ViewGroup parent) {

//Check if the convertViewis null, if it is null it probably means that this is the first time the view has been displayed

if (convertView == null)
{
convertView = View.inflate (context,R.layout.list_content_layout, null);
}
//If it is not null, you can just reuse it from the recycler
TextView txtcontent = (TextView) convertView.findViewById(R.id.txtcontent);
return convertView;
}