Save ArrayList using GSON on Android

When saving an ArrayList on Android, if it's as simple as using SQLite, It is convenient to convert it to JSON and save it in Preference.

Also, I think it will be easier to use GSON (Google library) when converting to JSON. https://github.com/google/gson

This time, convert the ʻArrayList `type and save it.

Introduction of GSON

Introduced gson library with gradle in Android Studio.

dependencies{
      ...
      ...
      compile 'com.google.code.gson:gson:2.7' //May be a little old
}

Read

private ArrayList<String> arrayList;
SharedPreferences pref = getSharedPreferences("pref", MODE_PRIVATE);
Gson gson = new Gson();
arrayList = gson.fromJson(pref.getString(SAVE_KEY, ""), new TypeToken<ArrayList<String>>(){}.getType());

If you want to branch the processing of the unsaved state to preference, like this

private ArrayList<String> arrayList;
SharedPreferences pref = getSharedPreferences("pref", MODE_PRIVATE);
Gson gson = new Gson();
String json = pref.getString(SAVE_KEY, "");
if(json.equals("[]"))
{
    arrayList = new ArrayList<>();
}
else
{
    arrayList = gson.fromJson(json, new TypeToken<ArrayList<String>>(){}.getType());
}

writing

SharedPreferences pref = getSharedPreferences("pref", MODE_PRIVATE);
Gson gson = new Gson();
pref.edit().putString(SAVE_KEY, gson.toJson(arrayList)).apply();

Recommended Posts

Save ArrayList using GSON on Android
Try using the service on Android Oreo
Sobel filter using OpenCV on Android (Java)
Try using Firebase Cloud Functions on Android (Java)
Android application development using Unity + ARCore on Ubuntu
Translator using Microsoft Translator Text API on Android ~ Implementation ~
Try communication using gRPC on Android + Java server
I tried using Gson
Using JDBC on Linux
Run the Android emulator on Docker using Android Emulator Container Scripts
Try image classification using TensorFlow Lite on Android (JAVA)
Using Flutter on Ubuntu (Part 2)
Customize list view on Android
Multipart transmission library on Android
[Rails] Save images using carrierwave
Use serial communication on Android
ROS app development on Android
Use native code on Android
Bubble sort using ArrayList (JAVA)
[Android] Convert Map to JSON using GSON in Kotlin and Java