BÀI 81 - LƯU MẢNG VÔ SHARED PREFERENCES TRONG ANDROID

  • Mình đã code và test oke hết ròi, bạn việc paste và sử dụng thôi.

public void saveArrayList(ArrayList<TenClass> list, String key){

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

SharedPreferences.Editor editor = prefs.edit();

Gson gson = new Gson();

String json = gson.toJson(list);

editor.putString(key, json);

editor.apply();

}


public ArrayList<TenClass> getArrayList(String key){

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

Gson gson = new Gson();

String json = prefs.getString(key, null);

Type type = new TypeToken <ArrayList<TenClass>>() {}.getType();

return gson.fromJson(json, type);

}