MAD
Assignment #07
Submitted to: MS Sadia Sahar
Submitted by: Group 1
Roll no’s: 15-188, 15-195, 15-201, 15-202, 15-238
Section: 6th, MB
Session: 2015-2019
Subject: Mobile Application Development
Course code: CSI-609
Topic: Base Adapter
Date: 20th November, 2018
Department: Computer Science
Computer Science Page 1
MAD
Customize ListView using BaseAdapter
In android, an adapter is a bridge between UI component and data source that helps us to fill
data in the UI component. It holds the data and send the data to adapter view then view can
takes the data from the adapter view and shows the data on different views like as list view,
grid view, spinner etc. For more customization of views we uses the base adapter. Now lets
discuss BaseAdapter class.
BaseAdapter is a common base class of a general implementation of an Adapter that
can be used in ListView, GridView, Spinner etc.
Whenever you need a customized list in a ListView or customized grids in a
GridView you create your own adapter and extend base adapter in that.
Base Adapter can be extended to create a custom Adapter for displaying a custom list
item.
Important Note: ArrayAdapter is also an implementation of BaseAdapter.
Here is the code of Custom Adapter when we extends the BaseAdapter in that:
Computer Science Page 2
MAD
In the above code snippet we see the overrided methods of BaseAdapter which are used to set
the data in a list, grid or a spinner. From there we mainly used two functions getCount() and
getView().
Let’s discuss all these functions in detail:
1. getCount():
The getCount() function returns the total number of items to be displayed in a list. It counts
the value from array list size() method or an array’s length. For example, if we have an list of
elements in an arraylist and we have to display the items in a list view then we can count the
total number of elements using the size function and then that integer value is returned by the
function getCount() as shown below.
2. getView(int i, View view, ViewGroup viewGroup):
This function is automatically called when the list item view is ready to be displayed or about
to be displayed. In this function we set the layout for list items using LayoutInflater class and
then add the data to the views like ImageView, TextView etc.
Below is the getView function’s example code with explanation included in which we set the
layout using LayoutInflater and then get the view’s id and implement them.
3. getItem(int i):
This function is used to Get the data item associated with the specified position in the data set
to obtain the corresponding data of the specific location in the collection of data items.
Below is the example code in which we returns the array list’s item according to position.
Computer Science Page 3
MAD
4. getItemId(int i):
As for the getItemId (int position), it returns the corresponding to the position item ID. The
function returns a long value of item position to the adapter.
Below is the code in which we returns the position.
Example of BaseAdapter to display list of countries in a ListView using Custom
BaseAdapter
In the below example we display list of countries with their flags using custom adapter to
show the usage of BaseAdapter. Below is the final output and code with explanation step by
step.
Computer Science Page 4
MAD
Step 1: Create a new project in Android Studio and name it BaseAdapterExample
Select File -> New -> New Project. Fill the forms and click "Finish" button.
Step 2: Now Open app -> res -> layout -> activity_main.xml (or) main.xml and add
following code:
Step 3: Now create another XML layout. In our case, we name it as activity_listview.xml.
Add the below code in it. Also make sure you have iclauncher image saved in drawable
folder or add it.
Computer Science Page 5
MAD
Step 4: Now open app -> java-> package -> MainActivity.java and add the below code.
Step 4: Create new class CustomAdapter.java and add following code
Computer Science Page 6
MAD
Output:
Now run the App in Emulator / AVD and you will see item country names with flags listed in
Listview.
Another example
Create model class
Each of our ListView rows will conatain an Item name and Item description, so our Model
class is as follows:
Item.java
Computer Science Page 7
MAD
ListView row layout
The xml file for the rows of the listview created in the res/layout folder is shown below:
layout_list_view_row_items.xml
Create the custom BaseAdapter implementation
Computer Science Page 8
MAD
Using the custom Adapter
The adapter can simply be used by instantiating it with the required paramters and set as the
listview's adapter.
Computer Science Page 9
MAD
ListView Optimization
To optimize the listview's performance, a new row layout should be inflated only when
convertView == null. This is because the adapter's getView method is called whenever the
listview needs to show a new row on the screen. The convertView gets recycled in this
process. Hence, the row layout should be inflated just once when convertView == null, and it
contents should be updated on subsequent getView calls, instead of inflating a new row on
each call which is very expensive.
Optimization using the ViewHolder pattern
One of the most common operation in Android is finding an inner view inside an inflated
layout. This is usually done using the findViewById method. This operation is not trivial
especially when the lisview has to frequently call getView when the list is scrolling.
The aim of the ViewHolder pattern, is to reduce the number of findViewById calls in the
adapter's getView. A ViewHolder is practically a lightweight inner class that holds direct
references to all inner views from a row.
It is then stored as a tag in the row's view after inflating it. This way you’ll only have to use
findViewById() when the layout is first created. Here’s a new implementation of our
adapter's getView with View Holder pattern applied:
Computer Science Page 10
MAD
References: https://abhiandroid.com/ui/baseadapter-tutorial-example.html
https://guides.codepath.com/android/Using-a-BaseAdapter-with-ListView
Class Example
MainActitivity.java Coding
package com.project.student.baseadapter;
import android.content.Context;
import android.content.res.Resources;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
/*
1 store all data members [titles, descriptions and
images]
2 define the structure of a single row of your listview
Computer Science Page 11
MAD
inside single_row.xml, a seperate xml file
3 define the listview inside main layout and reference
it in your activity
4 create your custom adapter that puts the data or each
row inside getView method
*/
ListView list;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list= (ListView) findViewById(R.id.listView);
list.setAdapter(new myAdapter(this));
}
/*
1 create a class that extends baseAdapter and
implement all the methods
2 Maintain some array inside you baseAdapter class
that will contain all the data
[titles+descriptions+images]
3 use the getView method to fill the data from your
array inside the custom structure of that single row
for each row
*/
class SingleRow
{
String title;
String description;
int image;
SingleRow(String title,String description,int
image)
{
this.title=title;
this.description=description;
this.image=image;
}
}
class myAdapter extends BaseAdapter
{
ArrayList<SingleRow> list;
Context context;
myAdapter(Context c)
{
context=c;
Computer Science Page 12
MAD
list=new ArrayList<SingleRow>();
/*
1 get the titles, descriptions and images
from xml
2 group each title, its related description
and image into a single row object
3 put the single row objects inside the
arraylist
*/
Resources res=c.getResources();
String[]
titles=res.getStringArray(R.array.titles);
String[]
descriptions=res.getStringArray(R.array.descriptions);
int[]
images={R.drawable.meme1,R.drawable.meme2,R.drawable.me
me3,R.drawable.meme4,R.drawable.meme5,R.drawable.meme6,
R.drawable.meme7,R.drawable.meme8,R.drawable.meme9,R.dr
awable.meme10,};
for(int i=0;i<10;i++)
{
list.add(new
SingleRow(titles[i],descriptions[i],images[i]));
}
}
/*
u1,u2,u3,u4
u1->title,description and image
*/
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int i) {
return list.get(i);
}
@Override
public long getItemId(int i) {
return 0;
Computer Science Page 13
MAD
@Override
public View getView(int i, View view, ViewGroup
viewGroup) {
/*
1 get the root view
2 use the root view to find other views
3 set the values
*/
LayoutInflater inflater=(LayoutInflater)
context.getSystemService(LAYOUT_INFLATER_SERVICE);
View
row=inflater.inflate(R.layout.single_row,viewGroup,fals
e);
TextView title=(TextView)
row.findViewById(R.id.textView1);
TextView description=(TextView)
row.findViewById(R.id.textView2);
ImageView image=(ImageView)
row.findViewById(R.id.imageView);
SingleRow obj=list.get(i);
title.setText(obj.title);
description.setText(obj.description);
image.setImageResource(obj.image);
return row;//return the rootView of your
single_row.xml
}
}
}
activity_main.xml Coding
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/andro
id"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
Computer Science Page 14
MAD
tools:context=".MainActivity">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/listView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"/>
</RelativeLayout>
strings.xml Coding
<resources>
<string name="app_name">baseADAPTER</string>
<string-array name="titles">
<item>Title 1</item>
<item>Title 2</item>
<item>Title 3</item>
<item>Title 4</item>
<item>Title 5</item>
<item>Title 6</item>
<item>Title 7</item>
<item>Title 8</item>
<item>Title 9</item>
<item>Title 10</item>
</string-array>
<string-array name="descriptions">
<item>Description 1</item>
<item>Description 2</item>
<item>Description 3</item>
<item>Description 4</item>
<item>Description 5</item>
<item>Description 6</item>
<item>Description 7</item>
<item>Description 8</item>
<item>Description 9</item>
<item>Description 10</item>
</string-array>
</resources>
Computer Science Page 15
MAD
single_row.xml Coding
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/andro
id"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/meme5"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:id="@+id/imageView"/>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/imageView"
android:layout_alignParentRight="true"
android:layout_toRightOf="@+id/imageView"
android:text="Meme 1"
android:textAppearance="?android:attr/textAppearanceLar
ge" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/imageView"
android:layout_alignParentRight="true"
android:layout_toRightOf="@+id/imageView"
android:text="Description 1"
android:textAppearance="?android:attr/textAppearanceSma
ll" />
</RelativeLayout>
Computer Science Page 16
MAD
Images can be copied from here
Optimization code is not added here. Its your assignment to add it in the above example.
Computer Science Page 17