Android BaseAdapter

BaseAdapter as the name suggests BaseAdapter is a base adapter, or super adapter. An adapter is a class that acts as a bridge between an adapterview and the underlying data source.

By being a base adapter BaseAdapter provides a common implementation for adapters that can be used in:

  1. ListView,GridView – By use of listAdapter.
  2. Spinner – By use of spinnerAdapter.

BaseAdapter Details

  1. BaseAdapter was introduced back in Android API level 1.
  2. It’s actually an abstract class in that it has some abstract methods that need overriding. Therefore you have to either choose to implement those methods or make your child class as well.
    public abstract class BaseAdapter ..{}
  3. BaseAdapter derives from java.lang.Object.
    public abstract class BaseAdapter extends Object ...{}
  4. BaseAdapter implements ListAdapter and SpinnerAdapter. SpinnerAdapter is used for spinners while ListAdapter for ListViews and GridViews.
    public abstract class BaseAdapter extends Object implements ListAdapter, SpinnerAdapter{..}

BaseAdapter Children and GrandChildren

BaseAdapter has several direct and indirect sub-classes.

No. Class Type Description
1. ArrayAdapter Direct While BaseAdapter is always abstract, this is a concrete implementation of BaseAdapter backed by an array of arbitrary objects.
2. SimpleAdapter Direct A BaseAdapter child we can use to provide mapping between static data to views defined in XML file.
3. CursorAdapter Direct A BaseAdapter child that exposes data from a cursor to a ListView.
4. ResourceCursorAdapter Indirect A CursorAdapter child that creates views defined in an XML file.
5. SimpleCursorAdapter Indirect A a ResourceCursorAdapter child that can map columns from Cursor or TextViews or ImageViews defined in an XML file.

 

Share

1 Example

  1. Android Custom Filter/Search ListView With Images Text [BaseAdapter]

    Hello good people,We cover how to perform a Custom Filter against data in your ListView.Our adapter is BaseAdapter and we shall be searching ListView with images and text.We shall implement Filterable interface and derive from Filter class.

    PLATFORM : Android Java
    TOOLS : Eclipse,Bluestacks Emulator

    SECTION 1 : Our Player Class.

    Purpose :

    1. Is our POJO class.Plain Old Java Object
    2. Holds data consisting of a single Player.
    package com.tutorials.listviewcustomfilterbase;
    
    public class Player {
    
      private String name;
      private int img;
    
      public Player(String name,int img) {
        // TODO Auto-generated constructor stub
    
        this.name=name;
        this.img=img;
      }
    
      public String getName() {
        return name;
      }
    
      public void setName(String name) {
        this.name = name;
      }
    
      public int getImg() {
        return img;
      }
    
      public void setImg(int img) {
        this.img = img;
      }
    }

    SECTION 2 : Our Custom Adapter class
    Purpose:

    1. Adapts our images and Text to our ListView
    2. Is where we bind data to views
    3. Has an inner class CustomFilter that implements Filtering or Searching for us.
    4. Implements Filterable method hence we override getFilter() method that in turn returns a filter object.
    package com.tutorials.listviewcustomfilterbase;
    
    import java.util.ArrayList;
    
    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.Filter;
    import android.widget.Filterable;
    import android.widget.ImageView;
    import android.widget.TextView;
    
    public class Adapter extends BaseAdapter implements Filterable{
    
      Context c;
      ArrayList<Player> players;
      CustomFilter filter;
      ArrayList<Player> filterList;
    
      public Adapter(Context ctx,ArrayList<Player> players) {
        // TODO Auto-generated constructor stub
    
        this.c=ctx;
        this.players=players;
        this.filterList=players;
      }
    
      @Override
      public int getCount() {
        // TODO Auto-generated method stub
        return players.size();
      }
    
      @Override
      public Object getItem(int pos) {
        // TODO Auto-generated method stub
        return players.get(pos);
      }
    
      @Override
      public long getItemId(int pos) {
        // TODO Auto-generated method stub
        return players.indexOf(getItem(pos));
      }
    
      @Override
      public View getView(int pos, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
    
        LayoutInflater inflater=(LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    
        if(convertView==null)
        {
          convertView=inflater.inflate(R.layout.model, null);
        }
    
        TextView nameTxt=(TextView) convertView.findViewById(R.id.nameTv);
        ImageView img=(ImageView) convertView.findViewById(R.id.imageView1);
    
        //SET DATA TO THEM
        nameTxt.setText(players.get(pos).getName());
        img.setImageResource(players.get(pos).getImg());
    
        return convertView;
      }
    
      @Override
      public Filter getFilter() {
        // TODO Auto-generated method stub
        if(filter == null)
        {
          filter=new CustomFilter();
        }
    
        return filter;
      }
    
      //INNER CLASS
      class CustomFilter extends Filter
      {
    
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
          // TODO Auto-generated method stub
    
          FilterResults results=new FilterResults();
    
          if(constraint != null && constraint.length()>0)
          {
            //CONSTARINT TO UPPER
            constraint=constraint.toString().toUpperCase();
    
            ArrayList<Player> filters=new ArrayList<Player>();
    
            //get specific items
            for(int i=0;i<filterList.size();i++)
            {
              if(filterList.get(i).getName().toUpperCase().contains(constraint))
              {
                Player p=new Player(filterList.get(i).getName(), filterList.get(i).getImg());
    
                filters.add(p);
              }
            }
    
            results.count=filters.size();
            results.values=filters;
    
          }else
          {
            results.count=filterList.size();
            results.values=filterList;
    
          }
    
          return results;
        }
    
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
          // TODO Auto-generated method stub
    
          players=(ArrayList<Player>) results.values;
          notifyDataSetChanged();
        }
    
      }
    
    }

    SECTION 3: Our MainActivity class:

    Purpose :

    1. Our launcher activity
    2. We set reference our ListView from XML and attach its BaseAdapter subclass to it.
    3. We reference our SearchView and implement its onQueryTextChangeListener.
    package com.tutorials.listviewcustomfilterbase;
    
    import java.util.ArrayList;
    
    import android.os.Bundle;
    import android.app.Activity;
    import android.view.Menu;
    import android.widget.ListView;
    import android.widget.SearchView;
    import android.widget.SearchView.OnQueryTextListener;
    
    public class MainActivity extends Activity {
    
      ListView lv;
      SearchView sv;
    
      String[] names={"Juan Mata","Ander Herera","Wayne Rooney","Eden Hazard","Michael Carrick","Diego Costa","Jose Mourinho"};
      int[] images={R.drawable.mata,R.drawable.herera,R.drawable.rooney,R.drawable.hazard,R.drawable.carrick,R.drawable.costa,R.drawable.mourinho};
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            lv=(ListView) findViewById(R.id.listView1);
            sv=(SearchView) findViewById(R.id.searchView1);
    
            //ADASPTER
            final Adapter adapter=new Adapter(this, getPlayers());
            lv.setAdapter(adapter);
    
            sv.setOnQueryTextListener(new OnQueryTextListener() {
    
          @Override
          public boolean onQueryTextSubmit(String arg0) {
            // TODO Auto-generated method stub
            return false;
          }
    
          @Override
          public boolean onQueryTextChange(String query) {
            // TODO Auto-generated method stub
    
            adapter.getFilter().filter(query);
    
            return false;
          }
        });
    
        }
    
        private ArrayList<Player> getPlayers()
        {
            ArrayList<Player> players=new ArrayList<Player>();
            Player p;
    
            for(int i=0;i<names.length;i++)
            {
                p=new Player(names[i], images[i]);
                players.add(p);
            }
    
            return players;
        }
    
    }

    SECTION 4 : Our ActivityMain.xml layout

    Purpose :

    1. Acts as our template Layout.
    2. Hold our ListView and SearchView
    <RelativeLayout 
        
        android_layout_width="match_parent"
        android_layout_height="match_parent"
        android_paddingBottom="@dimen/activity_vertical_margin"
        android_paddingLeft="@dimen/activity_horizontal_margin"
        android_paddingRight="@dimen/activity_horizontal_margin"
        android_paddingTop="@dimen/activity_vertical_margin"
        tools_context=".MainActivity" >
    
        <SearchView
            android_id="@+id/searchView1"
            android_layout_width="wrap_content"
            android_layout_height="wrap_content"
            android_layout_alignParentLeft="true"
            android_layout_alignParentTop="true"
            android_layout_alignRight="@+id/listView1"
            android_layout_marginLeft="14dp"
            android_queryHint="Search.." >
    
        </SearchView>
    
        <ListView
            android_id="@+id/listView1"
            android_layout_width="match_parent"
            android_layout_height="wrap_content"
            android_layout_alignParentLeft="true"
            android_layout_below="@+id/searchView1" >
    
        </ListView>
    
    </RelativeLayout>

    SECTION 4: Our Model.xml Layout Purpose :

    1. Acts as our Row Model.Remember we want to display Listview with images and text.So its how a single row in our ListView shall appear.
    2. Contains Images andText.
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout 
        android_layout_width="match_parent"
        android_layout_height="match_parent" >
    
        <ImageView
            android_id="@+id/imageView1"
            android_layout_width="wrap_content"
            android_layout_height="wrap_content"
            android_layout_alignParentLeft="true"
            android_layout_alignParentTop="true"
            android_layout_marginLeft="40dp"
            android_layout_marginTop="44dp"
            android_src="@drawable/ic_launcher" />
    
        <TextView
            android_id="@+id/nameTv"
            android_layout_width="wrap_content"
            android_layout_height="wrap_content"
            android_layout_alignTop="@+id/imageView1"
            android_layout_toRightOf="@+id/imageView1"
            android_text="Name"
            android_padding="10dp"
            android_textAppearance="?android:attr/textAppearanceMedium" />
    
    </RelativeLayout>

    Good day.




Share an Example

Share an Example

Browse
What is the capital of Egypt? ( Cairo )