Skip to content

Instantly share code, notes, and snippets.

@nolochemical
Last active May 16, 2018 01:37
Show Gist options
  • Save nolochemical/4aefff38c446053af3f369f69c919b5f to your computer and use it in GitHub Desktop.
Save nolochemical/4aefff38c446053af3f369f69c919b5f to your computer and use it in GitHub Desktop.
Android Room Type Converters For Slighty Complex Data - How to Use
/// start file Linkthing.class - used where your insert data
usage:
Collection col = new ArrayList();
col.add(new LP("ddg", "http://duckduckgo"));
// in db insert routine
...setLinkthing(col);
// You'll get something like this in your db rows .. SELECT * FROM linkthings WHERE links = ' [{"ddg", "http://duckduckgo"}] '
[{"ddg", "http://duckduckgo"}]
----=-----
class LP {
private String name;
private String link;
private void LP(String name, String link) {
this.name = name;
this.name = link;
}
public String getName() {
return name;
}
public String getLink() {
return link;
}
}
// end file //
/////start file JAVA1.class ////
// Fields in your database
...
@ColumnInfo(name = "linkthing", typeAffinity = ColumnInfo.TEXT)
private linkThing linkthing;
...
// Getters/Setters
...
class Converters {
@TypeConverters(Converters.class)
public linkThing getLinkthing() {
return this.linkthing;
}
@TypeConverters(Converters.class)
public void setLinkthing(@NonNull linkThing linkthing) {
this.linkthing = linkthing;
}
}
/////end file////
/////start file JAVA2.class ////
// database instantiation stuff is a decent place to put this or another file.. below we add the transmogifier
class Converters {
@TypeConverter
public static String fromLinkthing(linkThing value) {
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
return value == null ? null : gson.toJson(value);
}
@TypeConverter
public static linkThing fromString(String value) {
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
return value == null ? null : gson.fromJson(value, linkThing.class);
}
}
/////end file////
// Info about HashMap serialize to stream.. try typeAffinity = ColumnInfo.BLOB for this sort of thing, there be dragons
GSON - gson.excludeFieldsWithoutExposeAnnotation().create(); // learn how gson can `excludeFieldsWithoutExposeAnnotation`
https://www.techrepublic.com/blog/software-engineer/use-gson-to-work-with-json-in-your-android-apps/
https://beginnersbook.com/2013/12/how-to-serialize-hashmap-in-java/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment