Android Tutorial

Software Setup and Configuration

Android Studio

File Structure

Components

Core Topics

Layout

View

Button

Intent and Intent Filters

Toast

RecyclerView

Fragments

Adapters

Other UI Component

Image Loading Libraries

Date and Time

Material Design

Bars

Working with Google Maps

Chart

Animation

Database

Advance Android

Jetpack

Architecture

App Publish

App Monetization

How to Save ArrayList to SharedPreferences in Android?

SharedPreferences in Android is designed to store simple data types like int, float, boolean, long, and String. It doesn't natively support complex objects or collections like ArrayList. However, if you want to save an ArrayList to SharedPreferences, you can convert it into a String (like a JSON string) and then save it. Upon retrieval, you can parse the string back into an ArrayList.

Here's a simple way to achieve this using Google's Gson library:

1. Add Gson Dependency:

First, you need to add the Gson library dependency to your app's build.gradle:

implementation 'com.google.code.gson:gson:2.8.8'  // Check for the latest version

2. Save ArrayList to SharedPreferences:

public void saveArrayList(ArrayList<String> list, String key){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = prefs.edit();
    Gson gson = new Gson();
    String json = gson.toJson(list);
    editor.putString(key, json);
    editor.apply();
}

3. Retrieve ArrayList from SharedPreferences:

public ArrayList<String> getArrayList(String key){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    Gson gson = new Gson();
    String json = prefs.getString(key, null);
    Type type = new TypeToken<ArrayList<String>>() {}.getType();
    return gson.fromJson(json, type);
}

Replace ArrayList<String> with the type of ArrayList you have, if it's not a list of strings.

Notes:

  • Always consider the size of the data when using SharedPreferences. For large datasets, you may want to consider a different storage solution such as SQLite, Room, or external storage.

  • The reason we serialize the ArrayList is that SharedPreferences is meant to handle simple key-value pairs, and doesn't handle complex objects or collections natively.

  • Make sure the objects within the ArrayList are serializable. If you have custom objects in the ArrayList, ensure that they can be converted to a JSON string representation by Gson without issues.

  1. How to store ArrayList in SharedPreferences in Android:

    • Use SharedPreferences to store an ArrayList in Android:
    // Step 1: Get SharedPreferences instance
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    
    // Step 2: Save ArrayList to SharedPreferences
    ArrayList<String> myList = new ArrayList<>();
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString("key_list", new Gson().toJson(myList));
    editor.apply();
    
    // Step 3: Retrieve ArrayList from SharedPreferences
    String json = preferences.getString("key_list", null);
    ArrayList<String> retrievedList = new Gson().fromJson(json, new TypeToken<ArrayList<String>>(){}.getType());
    
  2. Saving and retrieving ArrayList from SharedPreferences:

    • Save and retrieve an ArrayList using SharedPreferences:
    // Save ArrayList
    ArrayList<String> myList = new ArrayList<>();
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString("key_list", new Gson().toJson(myList));
    editor.apply();
    
    // Retrieve ArrayList
    String json = preferences.getString("key_list", null);
    ArrayList<String> retrievedList = new Gson().fromJson(json, new TypeToken<ArrayList<String>>(){}.getType());
    
  3. SharedPreferences and ArrayList data persistence in Android:

    • Achieve data persistence with SharedPreferences and an ArrayList:
    // Save ArrayList
    ArrayList<String> myList = new ArrayList<>();
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString("key_list", new Gson().toJson(myList));
    editor.apply();
    
    // Retrieve ArrayList
    String json = preferences.getString("key_list", null);
    ArrayList<String> retrievedList = new Gson().fromJson(json, new TypeToken<ArrayList<String>>(){}.getType());
    
  4. Android SharedPreferences custom object (ArrayList) storage:

    • Extend the approach to store custom objects in SharedPreferences:
    // Save ArrayList of custom objects
    ArrayList<MyObject> myObjects = new ArrayList<>();
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString("key_objects", new Gson().toJson(myObjects));
    editor.apply();
    
    // Retrieve ArrayList of custom objects
    String json = preferences.getString("key_objects", null);
    ArrayList<MyObject> retrievedObjects = new Gson().fromJson(json, new TypeToken<ArrayList<MyObject>>(){}.getType());
    
  5. Using Gson to save ArrayList in SharedPreferences in Android:

    • Gson simplifies the serialization and deserialization process:
    // Save ArrayList using Gson
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString("key_list", new Gson().toJson(myList));
    editor.apply();
    
    // Retrieve ArrayList using Gson
    String json = preferences.getString("key_list", null);
    ArrayList<String> retrievedList = new Gson().fromJson(json, new TypeToken<ArrayList<String>>(){}.getType());
    
  6. ArrayList serialization and SharedPreferences in Android:

    • Serialize and deserialize an ArrayList for SharedPreferences:
    // Save ArrayList using serialization
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString("key_list", serialize(myList));
    editor.apply();
    
    // Retrieve ArrayList using deserialization
    String serialized = preferences.getString("key_list", null);
    ArrayList<String> retrievedList = deserialize(serialized);
    
    • Serialization and deserialization methods:
    private String serialize(ArrayList<String> list) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
            oos.writeObject(list);
            return Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    private ArrayList<String> deserialize(String serialized) {
        byte[] data = Base64.decode(serialized, Base64.DEFAULT);
        try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data))) {
            return (ArrayList<String>) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }
    
  7. Save and retrieve ArrayList of objects from SharedPreferences in Android:

    • Extend the approach to save and retrieve ArrayList of custom objects:
    // Save ArrayList of custom objects using Gson
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString("key_objects", new Gson().toJson(myObjects));
    editor.apply();
    
    // Retrieve ArrayList of custom objects using Gson
    String json = preferences.getString("key_objects", null);
    ArrayList<MyObject> retrievedObjects = new Gson().fromJson(json, new TypeToken<ArrayList<MyObject>>(){}.getType());