There are several built-in data structures in Android that developers can use to store and organize data in their applications. Some of the most commonly used data structures in Android include:
- Array: A fixed-size collection of elements of the same data type.
- ArrayList: A resizable array that can store elements of any data type.
- LinkedList: A doubly linked list data structure that allows for efficient insertion and deletion of elements.
- HashMap: A map data structure that stores key-value pairs and allows for fast lookups using the keys.
- SparseArray: Similar to a HashMap, but optimized for use with integer keys.
- SharedPreferences: A key-value storage system that allows for the storage of small amounts of data in the application’s private data storage.
These data structures are provided by the Android Framework, and developers can use them to store and retrieve data in their applications.
Using some of the data structures in Java and Kotlin:
Java
int[] myArray = new int[5];myArray[0] = 1;myArray[1] = 2; |
Kotlin
val myArray = intArrayOf(1, 2, 3, 4, 5) |
Java
ArrayList<String> myList = new ArrayList<>();myList.add("item1");myList.add("item2"); |
Kotlin
val myList = arrayListOf("item1", "item2", "item3") |
Java
LinkedList<Integer> myList = new LinkedList<>();myList.add(1);myList.add(2); |
Kotlin
val myList = LinkedList<Int>()myList.add(1)myList.add(2) |
Java
HashMap<String, Integer> myMap = new HashMap<>();myMap.put("key1", 1);myMap.put("key2", 2); |
Kotlin
val myMap = hashMapOf("key1" to 1, "key2" to 2) |
Java
SparseArray<String> mySparseArray = new SparseArray<>();mySparseArray.put(1, "item1");mySparseArray.put(2, "item2"); |
Kotlin
val mySparseArray = SparseArray<String>()mySparseArray.put(1, "item1")mySparseArray.put(2, "item2") |
Java
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);SharedPreferences.Editor editor = sharedPref.edit();editor.putString("key1", "value1");editor.apply(); |
Kotlin
val sharedPref = getPreferences(Context.MODE_PRIVATE)val editor = sharedPref.edit()editor.putString("key1", "value1")editor.apply() |
Example Android App
Below is a sample android app that uses an Array, ArrayList, LinkedList, HashMap, SparseArray, SharedPreferences, and SQLite to store and retrieve data.
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.
Step 2: Working with the activity_main.xml file
Navigate to app > res > layout > activity_main.xml and add the below code to it. Comments are added in the code to get to know in detail.
XML
<LinearLayout    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context=".MainActivity">      <TextView        android:id="@+id/array_text"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Array Element: " />      <TextView        android:id="@+id/arraylist_text"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="ArrayList Element: " />      <TextView        android:id="@+id/linkedlist_text"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="LinkedList Element: " />      <TextView        android:id="@+id/hashmap_text"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="HashMap Element: " />      <TextView        android:id="@+id/sparsearray_text"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="SparseArray Element: " />      <TextView        android:id="@+id/sharedpreferences_text"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="SharedPreferences Element: " />      <TextView        android:id="@+id/sqlite_text"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="SQLite Element: " />    </LinearLayout> |
Step 3: Working with the MainActivity fileÂ
Navigate to app > java > your app’s package name > MainActivity file and add the below code to it. Comments are added in the code to get to know in detail.Â
Kotlin
package com.gfg.android.kotlinproject  import android.os.Bundleimport android.util.SparseArrayimport android.widget.TextViewimport androidx.appcompat.app.AppCompatActivityimport java.util.*  class MainActivity : AppCompatActivity() {    private val myArray = intArrayOf(1, 2, 3)    private val myArrayList = ArrayList<String>()    private val myLinkedList = LinkedList<Any>()    private val myHashMap = HashMap<String, String>()    private val parsingArray = SparseArray<Any>()      override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_main)          // Find views by ID        val arrayText = findViewById<TextView>(R.id.array_text)        val arrayListText = findViewById<TextView>(R.id.arraylist_text)        val linkedListText = findViewById<TextView>(R.id.linkedlist_text)        val hashMapText = findViewById<TextView>(R.id.hashmap_text)        val sparseArrayText = findViewById<TextView>(R.id.sparsearray_text)        val sharedPreferencesText = findViewById<TextView>(R.id.sharedpreferences_text)        val sqliteText = findViewById<TextView>(R.id.sqlite_text)          // Initialize data for          // ArrayList and LinkedList        myArrayList.add("Hello")        myArrayList.add("World")        myLinkedList.add("Hello")        myLinkedList.add("World")          // Initialize data for HashMap        myHashMap["key1"] = "value1"        myHashMap["key2"] = "value2"          // Initialize data for SparseArray        parsingArray.put(1, "Hello")        parsingArray.put(2, "World")          // Initialize SharedPreferences        val sharedPreferences = getSharedPreferences("prefs", MODE_PRIVATE)        sharedPreferences.edit().putString("key", "value").apply()          // Initialize SQLite        val sqLiteDatabase = openOrCreateDatabase("mydb", MODE_PRIVATE, null)        sqLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS mytable (id INTEGER PRIMARY KEY, data TEXT)")        sqLiteDatabase.execSQL("INSERT INTO mytable (data) VALUES ('Hello World')")          // Display data in TextViews        arrayText.text = "Array Element: " + myArray[0]        arrayListText.text = "ArrayList Element: " + myArrayList[0]        linkedListText.text = "LinkedList Element: " + myLinkedList[0]        hashMapText.text = "HashMap Element: " + myHashMap["key1"]        sparseArrayText.text = "SparseArray Element: " + parsingArray[1]        sharedPreferencesText.text = "SharedPreferences Element: " + sharedPreferences.getString("key", "")          // Display data from SQLite        val cursor = sqLiteDatabase.rawQuery("SELECT * FROM mytable", null)        if (cursor.moveToFirst()) {            sqliteText.text = "SQLite Element: " + cursor.getString(1)        }        cursor.close()    }} |
Java
import android.content.SharedPreferences;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.os.Bundle;import android.widget.TextView;import androidx.appcompat.app.AppCompatActivity;import java.util.ArrayList;import java.util.HashMap;import java.util.LinkedList;  public class MainActivity extends AppCompatActivity {      private final int[] myArray = {1, 2, 3};    private final ArrayList<String> myArrayList = new ArrayList<>();    private final LinkedList<Object> myLinkedList = new LinkedList<>();    private final HashMap<String, String> myHashMap = new HashMap<>();    private final android.util.SparseArray<Object> parsingArray = new android.util.SparseArray<>();      @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);          // Find views by ID        TextView arrayText = findViewById(R.id.array_text);        TextView arrayListText = findViewById(R.id.arraylist_text);        TextView linkedListText = findViewById(R.id.linkedlist_text);        TextView hashMapText = findViewById(R.id.hashmap_text);        TextView sparseArrayText = findViewById(R.id.sparsearray_text);        TextView sharedPreferencesText = findViewById(R.id.sharedpreferences_text);        TextView sqliteText = findViewById(R.id.sqlite_text);          // Initialize data for          // ArrayList and LinkedList        myArrayList.add("Hello");        myArrayList.add("World");        myLinkedList.add("Hello");        myLinkedList.add("World");          // Initialize data for HashMap        myHashMap.put("key1", "value1");        myHashMap.put("key2", "value2");          // Initialize data for SparseArray        parsingArray.put(1, "Hello");        parsingArray.put(2, "World");          // Initialize SharedPreferences        SharedPreferences sharedPreferences = getSharedPreferences("prefs", MODE_PRIVATE);        sharedPreferences.edit().putString("key", "value").apply();          // Initialize SQLite        SQLiteDatabase sqLiteDatabase = openOrCreateDatabase("mydb", MODE_PRIVATE, null);        sqLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS mytable (id INTEGER PRIMARY KEY, data TEXT)");        sqLiteDatabase.execSQL("INSERT INTO mytable (data) VALUES ('Hello World')");          // Display data in TextViews        arrayText.setText("Array Element: " + myArray[0]);        arrayListText.setText("ArrayList Element: " + myArrayList.get(0));        linkedListText.setText("LinkedList Element: " + myLinkedList.get(0));        hashMapText.setText("HashMap Element: " + myHashMap.get("key1"));        sparseArrayText.setText("SparseArray Element: " + parsingArray.get(1));        sharedPreferencesText.setText("SharedPreferences Element: " + sharedPreferences.getString("key", ""));          // Display data from SQLite        Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM mytable", null);        if (cursor.moveToFirst()) {            sqliteText.setText("SQLite Element: " + cursor.getString(1));        }        cursor.close();    }} |
In this example, we are using an array to store integers, an ArrayList to store strings, a LinkedList to store objects, a HashMap to store key-value pairs, a SparseArray to store key-value pairs with integer keys, SharedPreferences to store simple data and SQLite to store complex data. We also show how to insert data into these data structures and how to retrieve data from these data structures using various methods. In the case of SQLite, we also show how to create a table and insert data into the table using SQLite database.
Note: In a real-world app, more robust methods and classes would be used for managing the SQLite database and for handling the data
Output:
Â
