Created
September 11, 2019 11:51
-
-
Save dynoChris/a9d4e0a4e5f86d8d66d63dc530565f9d to your computer and use it in GitHub Desktop.
How to persist object to room database in Android. How to persist list to room database in Android.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //Saving List. | |
| //If you want persist List you need implement TypeConverter | |
| //List<User> to json as string; json as string to List<User>. | |
| public class YourTypeConverterForPersistList { | |
| @TypeConverter | |
| public String listUsersToJson(List<User> users) { | |
| Gson gson = new Gson(); | |
| Type type = new TypeToken<List<User>>() {}.getType(); | |
| String json = gson.toJson(users, type); | |
| return json; | |
| } | |
| @TypeConverter | |
| public List<User> jsonToListUsers(String jsonListUsersAsString) { | |
| Gson gson = new Gson(); | |
| Type type = new TypeToken<List<User>>() {}.getType(); | |
| List<User> users = gson.fromJson(jsonListUsersAsString, type); | |
| return users; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //Saving object. | |
| //If you want persist some Object you need implement TypeConverter | |
| //Note: User to json as string; json as string to User. | |
| public class YourTypeConverterForPersistObject { | |
| @TypeConverter | |
| public String userToJson(User user) { | |
| return new Gson().toJson(user); | |
| } | |
| @TypeConverter | |
| public User jsonToUser(String jsonUserAsString) { | |
| return new Gson().fromJson(jsonAsString, User.class); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment