Custom ArrayAdapter Tutorial With Example In Android Studio






Custom ArrayAdapter Tutorial With Example In Android Studio


ArrayAdapter is a type of Adapter which acts a bridge between UI component and data source that helps us to fill data in UI component. It expects a Layout with a single TextView and for more customization in grid items or list items, we use custom adapters.
  • ArrayAdapter is also an implementation of BaseAdapter so if we want more customization then we create a custom adapter and extend ArrayAdapter in that.
  • We override all the function’s of BaseAdapter in our custom adapter to give more customization to ArrayAdapter.

Android Custom adapter code when we extends ArrayAdapter in that:
public class MyAdapter extends ArrayAdapter {

public MyAdapter(Context context, int resource, int textViewResourceId, List objects) {
super(context, resource, textViewResourceId, objects);
}

@Override
public int getCount() {
return super.getCount();
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
return super.getView(position, convertView, parent);
}
}
In the above code snippet we see the overrided functions of ArrayAdapter which are used to set the data in a list, grid or a spinner. From there we mainly used two functions getCount() and getView() .
1. getCount():
The getCount() function returns the total number of items to be displayed in a list. It counts the value from arraylist size or an array’s length. For example if we have an list of elements in a array list 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.
@Override
public int getCount() {

int count=arrayList.size(); //counts the total number of elements from the arrayList.
return count;//returns the total count to adapter
}
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.
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.activity_list_view, null);//set layout for displaying items
ImageView icon = (ImageView) view.findViewById(R.id.icon);//get id for image view
icon.setImageResource(countryFlags[i]);//set image of the item’s
return view;
}

Example of Custom ArrayAdapter:

Below is the example, in which we displays a list of animal names with images in a list view using simple array adapter. Below is the final output and code:

Step 1: Create a new project and name it ArrayAdapterExample.
Select File -> New -> New Project -> and Fill the forms and click "Finish" button
Step 2: Now open res -> layout -> xml (or) activity_main.xml and add following code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/simpleListView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:divider="#000"
        android:dividerHeight="2dp"/>

</RelativeLayout>
Step 3: Create a new layout in res-> layout and name it list_view_items.xml. Here add the following code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:padding="5dp"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:padding="@dimen/activity_horizontal_margin"
        android:text="Demo"
        android:textColor="#000" />
</LinearLayout>
Step 4: Now open app – > java -> package -> MainActivity.java and add the below code.
package example.abhiandriod.customarrayadapterexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ListView simpleList;
    ArrayList<Item> animalList=new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        simpleList = (ListView) findViewById(R.id.simpleListView);
        animalList.add(new Item("Lion",R.drawable.lion));
        animalList.add(new Item("Tiger",R.drawable.tiger));
        animalList.add(new Item("Monkey",R.drawable.monkey));
        animalList.add(new Item("Elephant",R.drawable.elephant));
        animalList.add(new Item("Dog",R.drawable.dog));
        animalList.add(new Item("Cat",R.drawable.cat));

        MyAdapter myAdapter=new MyAdapter(this,R.layout.list_view_items,animalList);
        simpleList.setAdapter(myAdapter);
       }
}
Step 5: Create a new Class app -> java ->package->MyAdapter.java and add the below code. Here in Custom Adapter class we override the function’s of BaseAdapter.
package example.abhiandriod.customarrayadapterexample;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;

public class MyAdapter extends ArrayAdapter<Item> {

    ArrayList<Item> animalList = new ArrayList<>();

    public MyAdapter(Context context, int textViewResourceId, ArrayList<Item> objects) {
        super(context, textViewResourceId, objects);
        animalList = objects;
    }

    @Override
    public int getCount() {
        return super.getCount();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View v = convertView;
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.list_view_items, null);
        TextView textView = (TextView) v.findViewById(R.id.textView);
        ImageView imageView = (ImageView) v.findViewById(R.id.imageView);
        textView.setText(animalList.get(position).getAnimalName());
        imageView.setImageResource(animalList.get(position).getAnimalImage());
        return v;

    }

}
Step 6: Create a new Class src-> package-> Item.java and add the below code:
package example.abhiandriod.customarrayadapterexample;


public class Item {

    String animalName;
    int animalImage;

    public Item(String animalName,int animalImage)
    {
        this.animalImage=animalImage;
        this.animalName=animalName;
    }
    public String getAnimalName()
    {
        return animalName;
    }
    public int getAnimalImage()
    {
        return animalImage;
    }
}

Output:
Now run the App in Emulator and you will see the animals name listed with images. For this we have used custom ArrayAdapter.

Example 2: Below is the example in which we display the animal images in grid’s of a grid view by using custom ArrayAdapter. Below is the final output and code:
Step 1: Create a new project and name it ArrayAdapterExample.
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 :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <GridView
        android:id="@+id/simpleGridView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
       android:numColumns="2"/>

</RelativeLayout>
Step 3: Create a new layout Activity in app -> res-> layout-> new activity and name it grid_view_items.xml and add following code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:layout_centerInParent="true"
        android:padding="5dp"
        android:scaleType="fitXY"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:padding="@dimen/activity_horizontal_margin"
        android:text="Demo"
        android:textColor="#000" />
</RelativeLayout>
Step 4: Now open app -> java -> package -> MainActivity.java
package example.abhiandriod.customarrayadapterexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.GridView;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    GridView simpleList;
    ArrayList<Item> animalList=new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        simpleList = (GridView) findViewById(R.id.simpleGridView);
        animalList.add(new Item("Lion",R.drawable.lion));
        animalList.add(new Item("Tiger",R.drawable.tiger));
        animalList.add(new Item("Monkey",R.drawable.monkey));
        animalList.add(new Item("Elephant",R.drawable.elephant));
        animalList.add(new Item("Dog",R.drawable.dog));
        animalList.add(new Item("Cat",R.drawable.cat));

        MyAdapter myAdapter=new MyAdapter(this,R.layout.grid_view_items,animalList);
        simpleList.setAdapter(myAdapter);
    }
}
Step 5: Create a new Class src -> package -> MyAdapter.java and add the following code:
package example.abhiandriod.customarrayadapterexample;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;

public class MyAdapter extends ArrayAdapter<Item> {

    ArrayList<Item> animalList = new ArrayList<>();

    public MyAdapter(Context context, int textViewResourceId, ArrayList<Item> objects) {
        super(context, textViewResourceId, objects);
        animalList = objects;
    }

    @Override
    public int getCount() {
        return super.getCount();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View v = convertView;
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.grid_view_items, null);
        TextView textView = (TextView) v.findViewById(R.id.textView);
        ImageView imageView = (ImageView) v.findViewById(R.id.imageView);
        textView.setText(animalList.get(position).getAnimalName());
        imageView.setImageResource(animalList.get(position).getAnimalImage());
        return v;

    }

}
Step 6: Create a new Class src -> package -> Item.java and add the below code:
package example.abhiandriod.customarrayadapterexample;

/**
 * Created by Gourav on 10-01-2016.
 */
public class Item {

    String animalName;
    int animalImage;

    public Item(String animalName,int animalImage)
    {
        this.animalImage=animalImage;
        this.animalName=animalName;
    }
    public String getAnimalName()
    {
        return animalName;
    }
    public int getAnimalImage()
    {
        return animalImage;
    }
}

ArrayAdapter Tutorial With Example In Android Studio

ArrayAdapter Tutorial With Example In Android Studio

In android, An adapter is a bridge between UI component and data source that helps us to fill data in 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 listview, gridview, spinner etc. ArrayAdapter is more simple and commonly used Adapter in android.
  • Whenever you have a list of single type of items which is backed by an array, you can use ArrayAdapter. For instance, list of phone contacts, countries or names.
  • By default, ArrayAdapter expects a Layout with a single TextView, If you want to use more complex views means more customization in grid items or list items, please avoid ArrayAdapter and use custom adapters.
Important Note: ArrayAdapter is an implementation of BaseAdapter so if we need to create a custom list view or  a grid view  then we have to create our own custom adapter and extend ArrayAdapter in that custom class. By doing this we can override  all the function’s of BaseAdapter in our custom adapter.
Here is code of ArrayAdapter in Android:
ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects)
In the above code snippet is the implementation of a ArrayAdapter. Below is the description of all the parameters used for the implementation of a ArrayAdapter to show a list of elements in a list view or in a spinner.
Parameters used in ArrayAdapter:
Lets discuss parameter in ArrayAdapter class:
  • context:
The first parameter is used to pass the context means the reference of current class. Here this is a keyword used to show the current class reference. We can also use getApplicationContext(), getActivity() in the place of this keyword. getApplicationContext() is used in a Activity and getActivity() is used in  a Fragment.
Below is the example code in which we set the current class reference in a adapter.
ArrayAdapter arrayAdapter = new ArrayAdapter(this, int resource, int textViewResourceId, T[] objects);
  • resource:
The second parameter is resource id used to set the layout(xml file) for list items in which you have a text view.
Below is the example code in which we set the layout.
ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.list_view_items, int textViewResourceId, T[] objects);
  • textViewResourceId:
The third parameter is textViewResourceId which is used to set the id of TextView where you want to display the actual text.
Below is the example code in which we set the id(identity) of a text view.
ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.list_view_items, R.id.textView, T[] objects);
  • objects:
The fourth parameter is an array of objects, used to set the array of elements in the textView. We can set the object of array or array list here.
Below is the example code in which we set the Animal array in adapter to display the Animal name’s list.
String animalList[] = {"Lion","Tiger","Monkey","Elephant","Dog","Cat","Camel"};
ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.list_view_items, R.id.textView, animalList);

Example of an ArrayAdapter:

Example 1: Below is the example, in which we displays a list of animal names in a list view using simple array adapter. Below is the final output and code:


Step 1: Create a new project and name it ArrayAdapterExample.
Open Android Studio -> Select File -> New -> New Project. Fill the forms and click "Finish" button.
Step 2: Now open app -> res -> layout -> xml (or) activity_main.xml and add following code :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/simpleListView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:divider="#000"
        android:dividerHeight="2dp"/>

</RelativeLayout>
Step 3: Create a new Activity activity_list_view.xml and add the below code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:padding="@dimen/activity_horizontal_margin"
        android:textColor="#000" />
</LinearLayout>
Step 4: Now Open app -> java -> package -> MainActivity.java and add the below code. Here we will use ArrayAdapter to display the items in Listview.
package example.abhiandriod.arrayadapterexample; //use package of your project

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {
    // Array of strings...
    ListView simpleList;
    String animalList[] = {"Lion","Tiger","Monkey","Elephant","Dog","Cat","Camel"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        simpleList = (ListView) findViewById(R.id.simpleListView);

        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.activity_list_view, R.id.textView, animalList);
        simpleList.setAdapter(arrayAdapter);
    }
       
    }
}
Output:
Now run the App in Emulator and you will see the below output:


Example 2: Below is the example, In which we display a list of Animal’s name in spinner using ArrayAadapter. Below is the final output and code:

Step 1: Create a new project and name it ArrayAdapterExample.
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:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Spinner
        android:id="@+id/animalNamesSpinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"/>

</RelativeLayout>
Step 3: Now create a new Activity simple_spinner_item.xml and add the below code:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@android:id/text1"
    style="?android:attr/spinnerItemStyle"
    android:singleLine="true"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:ellipsize="marquee"
    android:textAlignment="inherit"/>
Step 4: Now open app -> java -> package -> MainActivity.java and add the following code
package example.abhiandriod.arrayadapterexample;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends Activity implements
        AdapterView.OnItemSelectedListener {
    // Array of strings...
    String animalList[] = {"Lion", "Tiger", "Monkey", "Elephant", "Dog", "Cat", "Camel"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Getting the instance of Spinner and applying OnItemSelectedListener on it
        Spinner spin = (Spinner) findViewById(R.id.animalNamesSpinner);
        spin.setOnItemSelectedListener(this);

        //Creating the ArrayAdapter instance having the animal name's list
        ArrayAdapter aa = new ArrayAdapter(this, android.R.layout.simple_spinner_item, animalList);
        aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //Setting the ArrayAdapter data on the Spinner
        spin.setAdapter(aa);
    }


    //Performing action onItemSelected and onNothing selected
    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
        Toast.makeText(getApplicationContext(), animalList[position], Toast.LENGTH_LONG).show();
    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub

    }
}
Output:
Now run the App in Emulator / AVD and you will see the animals name listed in a Spinner

Custom SimpleAdapter Tutorial With Example In Android Studio

Custom SimpleAdapter Tutorial With Example In Android Studio

Whenever we have to create a custom list we need to implement custom adapter. As we discuss earlier ArrayAdapter is used when we have a list of single item’s backed by an Array. So if we need customization in a ListView or a GridView we need to implement simpleadapter but when we need even more customization in list or grid items where we have many view’s in a list item and also we have to perform any event like click or any other event to a particular view then we need to implement a custom adapter which fulfills our requirement. It is quite easy to implement.
Before moving further, it is important to do quick revision of Android SimpleAdapter which is an easy adapter to map static data to views defined in an XML file(layout). In android you can specify the data backing to a list as an ArrayList of Maps(hashmap or other). Each entry in an ArrayList is corresponding to one row of a list. The Maps contains  the data for each row. You also specify an XML file(custom list items file) that defines the views used to display the row, and a mapping from keys in the Map to specific views.
Important Note: We can’t perform events like click and other event on child item of a list or grid but if we have some requirements to do that then we can create our own custom adapter and extends the simpleadapter in that.

Table Of Contents [hide]
  • 1 Custom SimpleAdapter
  • 2 Example Of Custom SimpleAdapter in Android Studio:

Custom SimpleAdapter

BaseAdapter is the parent adapter for all other adapters so if we extends a SimpleAdapter then we can override the base adapter’s function in that class.
Android CustomAdapter code when we extends SimpleAdapter in that:
public class CustomAdapter extends SimpleAdapter {
public CustomAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
super(context, data, resource, from, to);

}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
return super.getView(position, convertView, parent);

}

@Override
public int getCount() {
return super.getCount();
}
}

In above code snippet we override functions of SimpleAdapter which are used to set the data in a list, grid or a spinner. There are few more methods but we mainly use these two method getCount() and getView().
1. getCount():
The getCount() function returns the total number of items to be displayed in a list. It counts the value from arraylist size or an array’s length. For example if we have a list of elements in a array list and we want to display the items in a listview then we can count the total number of those elements using the size function and that integer value is returned by the function getCount() as shown below.
@Override
public int getCount() {

int count=arrayList.size(); //counts the total number of elements from the arrayList.
return count;//returns the total count to adapter
}
2. getView(int i, View view, ViewGroup viewGroup):
This function is automatically called when the list item view is ready to be display or about to be display. In this function we set the layout for list items from the second parameter of this function i.e view.
Below is the getView function’s example code with explanation included. Here we set the layout and then perform the click event on a image view from that layout.
@Override
public View getView(int i, View view, ViewGroup viewGroup) {

View view=super.getView(position, convertView, parent);
ImageView imageView=(ImageView) view.findViewById(R.id.imageView);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(context, arrayList.get(position).get("name"), Toast.LENGTH_SHORT).show();
}
});
return view;
}

Example Of Custom SimpleAdapter in Android Studio:

In the below example of custom simple adapter we display the custom list of fruit names with their images in a list view where fruit image is displayed in the left side of the screen and the name is displayed to the right side of the image. When we click on a fruit image the name of the fruit is displayed.


Step 1: Create a new project in Android Studio and name it CustomSimpleAdapterExample.
Select File -> New -> New Project and Fill the forms and click "Finish" button.
Step 2: Open app  -> res -> layout -> xml (or) activity_main.xml and add following code. Here we are creating ListView inside RelativeLayout.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<ListView
android:id="@+id/simpleListView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="#000"
android:dividerHeight="2dp" />

</RelativeLayout>
Step 3: Now Create new a new layout Activity. Go to res-> right click on layout -> New -> Activity -> Blank Activity and create list_view_items.xml and add following code. Here we are creating items view that will be displayed inside each row.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff">

<ImageView
android:id="@+id/imageView"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_marginLeft="10dp"
android:padding="5dp"
android:src="@drawable/ic_launcher" />

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="@dimen/activity_horizontal_margin"
android:text="Demo"
android:textColor="#000" />
</LinearLayout>
Step 4: Now open app -> java -> package -> MainActivity.java and add the following code. Explanation is added in the code itself:
package example.abhiandriod.customsimpleadapterexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    //initialize view's
    ListView simpleListView;
    String[] fruitsNames = {"Apple", "Banana", "Litchi", "Mango", "PineApple"};//fruit names array
    int[] fruitsImages = {R.drawable.apple, R.drawable.banana, R.drawable.litchi, R.drawable.mango, R.drawable.pineapple};//fruits images array

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        simpleListView = (ListView) findViewById(R.id.simpleListView);

        ArrayList<HashMap<String, String>> arrayList = new ArrayList<>();
        for (int i = 0; i < fruitsNames.length; i++) {
            HashMap<String, String> hashMap = new HashMap<>();//create a hashmap to store the data in key value pair
            hashMap.put("name", fruitsNames[i]);
            hashMap.put("image", fruitsImages[i] + "");
            arrayList.add(hashMap);//add the hashmap into arrayList
        }
        String[] from = {"name", "image"};//string array
        int[] to = {R.id.textView, R.id.imageView};//int array of views id's
        CustomAdapter simpleAdapter = new CustomAdapter(this, arrayList, R.layout.list_view_items, from, to);//Create object and set the parameters for simpleAdapter
        simpleListView.setAdapter(simpleAdapter);//sets the adapter for listView

        //perform listView item click event
        simpleListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(getApplicationContext(), fruitsNames[i], Toast.LENGTH_LONG).show();//show the selected image in toast according to position
            }
        });

    }
    
}
Step 5: Now create New Class. Go to app -> java -> right click on package-> New -> Java Class and create CustomAdapter.java and add following code. Here we extends SimpleAdapter in CustomAdapter class and override the methods of BaseAdapter since it is the parent adapter for all other adapters.
package example.abhiandriod.customsimpleadapterexample;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;

public class CustomAdapter extends SimpleAdapter {
LayoutInflater inflater;
Context context;
ArrayList<HashMap<String, String>> arrayList;

public CustomAdapter(Context context, ArrayList<HashMap<String, String>> data, int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
this.context = context;
this.arrayList = data;
inflater.from(context);
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(context, arrayList.get(position).get("name"), Toast.LENGTH_SHORT).show();
}
});
return view;
}

}
Output:
Now start AVD in Emulator and run the App. You will see the custom list of fruit names with their images in a list view. Click on any fruit to see its name displayed on screen as Toast message.

SimpleAdapter Tutorial With Examples In Android Studio

SimpleAdapter Tutorial With Examples In Android Studio

In android, An adapter is a bridge between UI component and data source that helps us to fill data in UI component. SimpleAdpater is used for customization of list or grid items.
In Android, SimpleAdapter is an easy adapter to map static data to views defined in an XML file (layout). In android you can specify the data backing to a list as an ArrayList of Maps(hashmap or other). Each entry in a ArrayList is corresponding to one row of a list. The Map contains the data for each row. You also specify an XML file(custom list items file) that defines the views used to display the row, and a mapping from keys in the Map to specific views. This whole thing will make sense when you do one example in Android Studio as discussed at the end of this article.
Whenever we have to create a custom list we need to implement custom adapter. As we discuss earlier ArrayAdapter is used when we have a list of single item’s backed by an Array. So if we need more customization in a ListView or a GridView we need to implement simple adapter.
Below is android SimpleAdapter code:
SimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)
In above code snippet we show the implementation of a SimpleAdapter. Below is the description of all the parameters used for the implementation of a SimpleAdapter to show a list of elements in a list view or in a grid view.
Parameters used in SimpleAdapter:
1. context:
The first parameter is used to pass the context means the reference of current class. Here this is a keyword used to show the current class reference. We can also use getApplicationContext(), getActivity() in the place of this keyword. getApplicationContext() is used in a Activity and getActivity() is used in  a Fragment.
Below is the example code in which we set the current class reference in a adapter.
SimpleAdapter(this, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)
2. data:
The second parameter is data which is a List of Maps. Each entry in a List corresponds to one row in the list. The Maps contains the data of each row and should include all the entries specified in “from” string array.
Below is the example, In which we set’s the map type arrayList.
SimpleAdapter(this, hashmapData, int resource, String[] from, int[] to)
3. resource:
The third parameter is resource id which is use to set the layout (xml file) for list items in which you have a text view, image view or any other view.
Below is the example code in which we set the layout (xml file) for creating custom list.
Suppose below is the code of Activity custom_list_items.xml where we define ImageView and TextView as list items which will be set in Layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:padding="5dp"
        android:layout_alignParentRight="true"
        android:layout_marginRight="10dp"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="@dimen/activity_horizontal_margin"
        android:text="Demo"
        android:textColor="#000" />
</RelativeLayout>

Now we will pass this layout as 3rd parameter in SimpleAdapter.
SimpleAdapter (this, hashmapData, R.layout.custom_list_items, String[] from, int[] to) 
4. from:
The fourth parameter is from is an string array or called a list of column names that will be added to a Map associated with each item of a grid or list view.
Below is the example code in which we set an array for list items
String fromArray[]={"userName","userImage"};
SimpleAdapter (this, hashmapData, R.layout.custom_list_items, fromArray, int[] to)
5. to:
The fifth and last parameter is to which is an integer array used to store the Id’s of the views. The views that should display column in the “from” parameter. These should all be TextViews. The first N views in this list are given the values of the first N columns in the “from” parameter.
Below is the example code, In which we set the integer array for views id’s.
int to[]={R.id.textView,R.id.imageView};

SimpleAdapter (this, hashmapData, R.layout.custom_list_items, fromArray,to)

Example of Simple Adapter in Android Studio:

In below example of simple adapter we display the custom list of animal names with their images in a list view. Here animal image is displayed in the right side of the screen and the name is displayed to the left side of the screen. When you click on any list item the animal name from that item will be displayed as a Toast to screen. Below is the final output and code:

Step 1: Create a new project in Android Studio and name it SimpleAdapterExample.
Select File -> New -> New Project and Fill the forms and click "Finish" button.
Step 2: Now go to res -> layout -> xml (or) activity_main.xml and add following code. Here we are designing ListView in Relative Layout.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/simpleListView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:divider="#000"
        android:dividerHeight="2dp"
        android:listSelector="#600"/>

</RelativeLayout>
Step 3: Now Create a new Activity. Go to res-> right click on layout-> new -> Activity -> Blank Activity and create list_view_items.xml activity. Here add following code. Here we are defining ImageView and TextView items that will be displayed inside each row of ListView.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:padding="5dp"
        android:layout_alignParentRight="true"
        android:layout_marginRight="10dp"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="@dimen/activity_horizontal_margin"
        android:text="Demo"
        android:textColor="#000" />
</RelativeLayout>

Step 4: Now open app -> java -> package, click on MainActivity.java and add the below code. Here we will use SimpleAdapter to display static data in XML layout. More explanation is included in the code itself.
package example.abhiandriod.simpleadapterexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    //initialize view's
    ListView simpleListView;
    String[] animalName={"Lion","Tiger","Monkey","Dog","Cat","Elephant"};//animal names array
    int[] animalImages={R.drawable.lion,R.drawable.tiger,R.drawable.monkey,R.drawable.dog,R.drawable.cat,R.drawable.elephant};//animal images array
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        simpleListView=(ListView)findViewById(R.id.simpleListView);

        ArrayList<HashMap<String,String>> arrayList=new ArrayList<>();
        for (int i=0;i<animalName.length;i++)
        {
            HashMap<String,String> hashMap=new HashMap<>();//create a hashmap to store the data in key value pair
            hashMap.put("name",animalName[i]);
            hashMap.put("image",animalImages[i]+"");
            arrayList.add(hashMap);//add the hashmap into arrayList
        }
        String[] from={"name","image"};//string array
        int[] to={R.id.textView,R.id.imageView};//int array of views id's
        SimpleAdapter simpleAdapter=new SimpleAdapter(this,arrayList,R.layout.list_view_items,from,to);//Create object and set the parameters for simpleAdapter
        simpleListView.setAdapter(simpleAdapter);//sets the adapter for listView

        //perform listView item click event
        simpleListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(getApplicationContext(),animalName[i],Toast.LENGTH_LONG).show();//show the selected image in toast according to position
            }
        });
    }

    
}
Output:
Now run the App in AVD or Emulator and you will see the ListView displaying animal names and images. Now click on the any Animal and you will see Toast message showing Animal name.

BaseAdapter Tutorial With Example In Android Studio

BaseAdapter Tutorial With Example In Android Studio

Before we share BaseAdapter it is first important to revise Adapter. 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 customisation 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:
public class CustomAdapter extends BaseAdapter {

@Override
public int getCount() {
return 0;
}

@Override
public Object getItem(int i) {
return null;
}

@Override
public long getItemId(int i) {
return 0;
}

@Override
public View getView(int i, View view, ViewGroup viewGroup) {

return null;
}
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.
@Override
public int getCount() {
int count=arrayList.size(); //counts the total number of elements from the arrayList
return count;//returns the total count to adapter
}
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.
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.activity_gridview, null);//set layout for displaying items
ImageView icon = (ImageView) view.findViewById(R.id.icon);//get id for image view
icon.setImageResource(flags[i]);//set image of the item’s
return view;
}
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.
@Override
public Object getItem(int i) {
return arrayList.get(i);
}
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.
@Override
public long getItemId(int i) {
return i;
}

Table Of Contents [hide]
      • 0.0.1 BaseAdapter Example In Android Studio:
  • 1 SignUp To Download BaseAdapter Code
  • 2 Signup! To Download BaseAdapter Code

BaseAdapter Example In Android Studio:

Example 1: Example of BaseAdapter for displaying Animal images in grids using GridView.
In the below example we display animals images in the form of grids using custom adapter to show the usage of BaseAdapter. Below is the final output and code with explanation:
Step 1: Create a new project and name it BaseAdapterExample.
Step 2: Now open res -> layout -> activity_main.xml (or) main.xml and add following code. Here we will create Gridview inside LinearLayout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<GridView
android:id="@+id/simpleGridView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:footerDividersEnabled="false"
android:numColumns="3" />
</LinearLayout>
Step 3: Create a new Activity activity_gridview.xml inside layout and add the below code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/icon"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:scaleType="fitXY"
        android:layout_margin="5dp"
        android:layout_gravity="center_horizontal" />
</LinearLayout>
Step 3: Now open app -> java -> package -> MainActivity.java and add the below code. Make sure you have images saved in drawable folder with the names we have used or else change the name based on the images present in your drawable folder.
package example.abhiandriod.baseadapterexample;

import android.app.Activity;
import android.os.Bundle;
import android.widget.GridView;

public class MainActivity extends Activity {

GridView simpleGrid;
int animals[] = {R.drawable.animal13, R.drawable.animal14, R.drawable.animal15, R.drawable.animal16, R.drawable.animal17, R.drawable.animal18, R.drawable.animal15, R.drawable.animal16, R.drawable.animal17};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
simpleGrid = (GridView) findViewById(R.id.simpleGridView);
CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), animals);
simpleGrid.setAdapter(customAdapter);
}
}
Step 4: Create a new class CustomAdapter.java inside package and add the following code
package example.abhiandriod.baseadapterexample; //Use your package

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

public class CustomAdapter extends BaseAdapter {
Context context;
int animals[];
LayoutInflater inflter;

public CustomAdapter(Context applicationContext, int[] animals) {
this.context = applicationContext;
this.animals = animals;
inflter = (LayoutInflater.from(applicationContext));
}

@Override
public int getCount() {
return animals.length;
}

@Override
public Object getItem(int i) {
return null;
}

@Override
public long getItemId(int i) {
return 0;
}

@Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.activity_gridview, null);
ImageView icon = (ImageView) view.findViewById(R.id.icon);
icon.setImageResource(animals[i]);
return view;
}
}
Output:
Now run the App in Emulator / AVD and you will see Animals listed in Grids. So this is one use of BaseAdapter in Gridview.

Example 2: 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.
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 :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ListView
        android:id="@+id/simpleListView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:divider="@color/material_blue_grey_800"
        android:dividerHeight="1dp"
        android:footerDividersEnabled="false" />
</LinearLayout>
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.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/icon"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:padding="@dimen/activity_horizontal_margin"
        android:textColor="#000" />
</LinearLayout>
Step 4: Now open app -> java-> package -> MainActivity.java and add the below code.
package example.abhiandriod.baseadapterexample;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;

public class MainActivity extends Activity {

    ListView simpleList;
    String countryList[] = {"India", "China", "australia", "Portugle", "America", "NewZealand"};
    int flags[] = {R.drawable.india, R.drawable.china, R.drawable.australia, R.drawable.portugle, R.drawable.america, R.drawable.new_zealand};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        simpleList = (ListView) findViewById(R.id.simpleListView);
        CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), countryList, flags);
        simpleList.setAdapter(customAdapter);
    }
}
Step 4: Create new class CustomAdapter.java and add following code
package example.abhiandriod.baseadapterexample;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;


public class CustomAdapter extends BaseAdapter {
    Context context;
    String countryList[];
    int flags[];
    LayoutInflater inflter;

    public CustomAdapter(Context applicationContext, String[] countryList, int[] flags) {
        this.context = context;
        this.countryList = countryList;
        this.flags = flags;
        inflter = (LayoutInflater.from(applicationContext));
    }

    @Override
    public int getCount() {
        return countryList.length;
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        view = inflter.inflate(R.layout.activity_listview, null);
        TextView country = (TextView) view.findViewById(R.id.textView);
        ImageView icon = (ImageView) view.findViewById(R.id.icon);
        country.setText(countryList[i]);
        icon.setImageResource(flags[i]);
        return view;
    }
}
Output:
Now run the App in Emulator / AVD and you will see item country names with flags listed in Listview.

How to extract filename from Uri?

Now, we can extract filename with and without extension :) You will convert your bitmap to uri and get the real path of your file. Now w...