Saving array of custom objects to SharedPreferences on Android

On iOS when you store an object in UserDefaults, you just put it there via setValueForKey, and it doesn't matter if you put the class there on its own, or an array of your custom classes. What matters is when you get it (them) back via objectForKey or arrayForKey, you cast the object(s) into a correct type/array of types.

On Android the principle is similar with the primitives (ints, strings, booleans, etc.) but it gets a bit tricky from an iOS-dev's perspective to store an array of objects in SharedPreferences (Android's analog for iOS's UserDefaults), but there is a solution.

First, we save your array (list) of objects:

// Needed libraries
import android.content.Context;
import android.content.SharedPreferences;
import java.lang.reflect.Type;
import java.util.List;

// Accessing SharedPreferences
SharedPreferences sp = getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();

// Saving accounts
public void saveAccounts(List<Account> accounts) {
    Gson gson = new Gson();
    String accountsJson = gson.toJson(accounts);
    editor.putString(r.getString("SavedAccounts"), accountsJson);

As you can see, even though we pass an array of objects, we then convert and store them actually as a string. Nothing unusual here, except storing an array of objects as a string 🙂

Where it gets interesting is when we need to get the objects back from SharedPreferences:

public List<Account> getAccounts() {
    Gson gson = new Gson();
    Type type = new TypeToken<List<Account>>(){}.getType();
    String accountsString = sharedPref.getString("SavedAccounts", "");
    return gson.fromJson(accountsString, type);

Here we get our array of objects as a string and convert it back to our list of accounts via Gson's built-in functionality.