Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavaSimpleAdapter in Android with Example

SimpleAdapter in Android with Example

In Android, whenever we want to bind some data which we get from any data source (e.g. ArrayList, HashMap, SQLite, etc.) with a UI component(e.g. ListView, GridView, etc.) then Adapter comes into the picture. Basically Adapter acts as a bridge between the UI component and data sources. Here Simple Adapter is one type of Adapter. It is basically an easy adapter to map static data to views defined in our XML file(UI component) and is used for customization of List or Grid items. Here we use an ArrayList of Map (e.g. hashmap, mutable map, etc.) for data-backing. Each entry in an ArrayList is corresponding to one row of a list. The Map contains the data for each row. Now to display the row we need a view for which we used to specify a custom list item file (an XML file).

General Syntax of SimpleAdapter

SimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)

***Here context, data, resource, from, and to are five parameters***        

 

Parameters                                        

DataType

Explanation

context Context When we make an object of SimpleAdapter class  It is used to pass the context ( The reference of current activity). 
data

List<? extends Map<String, ?>>

*** it means a List of Maps whose key‘s type is String and Value can be any datatype.

Each element of the List is different Maps that contain the data of each row and should include all the entries specified in the “from” string array. In our project, we shall use ArrayList.
resource

 int

***Integer Datatype

This parameter is used to pass the resource id of the layout ( XML file ) which should contain the different views of each row of the list. The layout file should include at least those named views defined in “to”.
from An array of String type A list of column names that will be added to the Map associated with each item. In this array, there should be a column name for each item (Views) of each row of the list.
to An array of int type. This array parameter stores the ids of different views that should display the 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.

Example

A sample image is given below to get an idea about what we are going to do in this article. In this project, we are going to make this application which has a list of some fruits and in each row of the list has a fruit image and name. Note that we are going to implement this same project in both Kotlin and Java languages. Now you choose your preferred language.  

SimpleAdapter in Android with Example

Step by Step Implementation

Step 1: Create a New Project

Open Android Studio > Create New Project > Select an Empty Activity > Give a project name (Here our project name is “GFG_SimpleAdapter“).

*** Here you can choose either Kotlin or Java which you preferred and choose the API level according to your choice.

***After creating the project successfully, please paste some pictures into the drawable folder in the res directory. Now you can use the same pictures which I have used in my project otherwise you can choose pictures of your own choice. To download the same pictures please click on the below-given link:

CLICK HERE

***please note that it is optional***

Step 2: Working with the activity_main.xml file

In the activity_main.xml file, create a ListView inside a RelativeLayout. Below is the code for the activity_main.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
     
    <!--Creating a ListView-->
    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:divider="#000000"
        android:dividerHeight="3dp"
        android:padding="5dp" />
 
</RelativeLayout>


activity_main.xml Interface:

Step 3: Create another XML file (named list_row_items) and create UI for each row of the ListView

Create a new Layout Resource file and name it as list_row_items.  

Below is the code for the list_row_items.xml file. 

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
     
    <!--Creating a ImageView-->
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="120dp"
        android:layout_height="120dp"
        android:layout_margin="10dp"
        android:scaleType="fitCenter"
        android:src="@drawable/ic_launcher_background" />
     
    <!--Creating a TextView-->
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:layout_marginRight="20dp"
        android:layout_toRightOf="@+id/imageView"
        android:gravity="center"
        android:padding="5dp"
        android:text="Text View"
        android:textColor="#808080"
        android:textSize="40sp"
        android:textStyle="bold|italic" />
     
</RelativeLayout>


list_row_items.xml Interface:

Step 4: Working with the MainActivity file 

Here we will show you how to implement SimpleAdapter both in Java and Kotlin. Now you choose your preferred one. Below is the code for the MainActivity file. Comments are added inside the code to understand the code in more detail. 

Java




import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.HashMap;
 
public class MainActivity extends AppCompatActivity {
 
    ListView listView;
 
    // creating  a String type array (fruitNames)
    // which contains names of different fruits' images
    String fruitNames[] = {"Banana", "Grape", "Guava", "Mango", "Orange", "Watermelon"};
 
    // creating an Integer type array (fruitImageIds) which
    // contains IDs of different fruits' images
    int fruitImageIds[] = {R.drawable.banana,
            R.drawable.grape,
            R.drawable.guava,
            R.drawable.mango,
            R.drawable.orange,
            R.drawable.watermelon};
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // Binding the ListView  of activity_main.xml file
        // with this java code in MainActivity.java
        listView = findViewById(R.id.listView);
 
        // creating an ArrayList of HashMap.The kEY of the HashMap
        // is a String and VALUE is of any datatype(Object)
        ArrayList<HashMap<String, Object>> list = new ArrayList<>();
 
        // By a for loop, entering different types of data in HashMap,
        // and adding this map including it's datas into the ArrayList
        // as list item and this list is the second parameter of the SimpleAdapter
        for (int i = 0; i < fruitNames.length; i++) {
 
            // creating an Object of HashMap class
            HashMap<String, Object> map = new HashMap<>();
 
            // Data entry in HashMap
            map.put("fruitName", fruitNames[i]);
            map.put("fruitImage", fruitImageIds[i]);
 
            // adding the HashMap to the ArrayList
            list.add(map);
        }
 
        // creating A string type array(from) which contains
        // column names for each View in each row of the list
        // and this array(form) is the fourth parameter of the SimpleAdapter
        String[] from = {"fruitName", "fruitImage"};
 
        // creating an integer type array(to) which contains
        // id of each View in each row of the list
        // and this array(form) is the fifth parameter of the SimpleAdapter
        int to[] = {R.id.textView, R.id.imageView};
 
        // creating an Object of SimpleAdapter class and
        // passing all the required parameters
        SimpleAdapter simpleAdapter = new SimpleAdapter(getApplicationContext(), list, R.layout.list_row_items, from, to);
 
        // now setting the simpleAdapter to the ListView
        listView.setAdapter(simpleAdapter);
    }
}


Kotlin




import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ListView
import android.widget.SimpleAdapter
import java.util.ArrayList
import java.util.HashMap
 
class MainActivity : AppCompatActivity() {
   
    private lateinit var listView:ListView
   
    // creating  a String type array
      // (fruitNames) which contains
    // names of different fruits' images
    private val fruitNames=arrayOf("Banana","Grape","Guava","Mango","Orange","Watermelon")
     
    // creating an Integer type array (fruitImageIds) which
    // contains IDs of different fruits' images
    private val fruitImageIds=arrayOf(R.drawable.banana,
                              R.drawable.grape,
                              R.drawable.guava,
                              R.drawable.mango,
                              R.drawable.orange,
                              R.drawable.watermelon) 
     
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
         
        // ViewBinding the ListView  of activity_main.xml file
        // with this kotlin code in MainActivity.kt
        listView=findViewById(R.id.listView)
         
        // creating an ArrayList of HashMap.The kEY of the HashMap is
        // a String and VALUE is of any datatype(Any)
        val list=ArrayList<HashMap<String,Any>>()
         
        // By a for loop, entering different types of data in HashMap,
        // and adding this map including it's datas into the ArrayList
        // as list item and this list is the second parameter of the SimpleAdapter
        for(i in fruitNames.indices){
            val map=HashMap<String,Any>()
             
            // Data entry in HashMap
            map["fruitName"] = fruitNames[i]
            map["fruitImage"]=fruitImageIds[i]
           
            // adding the HashMap to the ArrayList
            list.add(map)
        }
         
        // creating A string type array(from) which contains
        // column names for each View in each row of the list
        // and this array(form) is the fourth parameter of the SimpleAdapter
        val from=arrayOf("fruitName","fruitImage")
         
        // creating an integer type array(to) which contains
        id of each View in each row of the list
        and this array(form) is the fifth parameter of the SimpleAdapter*/
         
        val to= intArrayOf(R.id.textView,R.id.imageView)
         
        // creating an Object of SimpleAdapter
          // class and passing
        // all the required parameters
        val simpleAdapter=SimpleAdapter(this,list,R.layout.list_row_items,from,to)
         
        // now setting the simpleAdapter
          // to the ListView
        listView.adapter = simpleAdapter
    }
}


Thus SimpleAdapter holds data and sends the data to the adapter view then the view can take the data from the adapter view and shows the data on the ListView which we have created earlier. 

***Please note you have to choose any one language between Java and Kotlin as MainActivity for a  particular project***

Output:

RELATED ARTICLES

Most Popular

Recent Comments