-
-
Save electrolobzik/b842b92e46aad24c0c92 to your computer and use it in GitHub Desktop.
This file contains 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
// TypeToken is a Gson class | |
Type type = new TypeToken<List<Author>>(){}.getType(); | |
GsonFieldConverterFactory factory = new GsonFieldConverterFactory(type); | |
// Register the factory and set the instance as the global Cupboard instance | |
CupboardFactory.setCupboard(new CupboardBuilder().registerFieldConverterFactory(factory).build()); |
This file contains 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
import com.google.gson.Gson; | |
import android.content.ContentValues; | |
import android.database.Cursor; | |
import java.lang.reflect.Type; | |
import nl.qbusict.cupboard.convert.EntityConverter; | |
import nl.qbusict.cupboard.convert.FieldConverter; | |
public class GsonFieldConverter<T> implements FieldConverter<T> { | |
private final Gson mGson; | |
private final Type mType; | |
public GsonFieldConverter(Gson gson, Type type) { | |
mGson = gson; | |
mType = type; | |
} | |
@Override | |
public T fromCursorValue(Cursor cursor, int columnIndex) { | |
return mGson.fromJson(cursor.getString(columnIndex), mType); | |
} | |
@Override | |
public EntityConverter.ColumnType getColumnType() { | |
return EntityConverter.ColumnType.TEXT; | |
} | |
@Override | |
public void toContentValue(T value, String key, ContentValues values) { | |
values.put(key, mGson.toJson(value)); | |
} | |
} |
This file contains 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
import com.google.gson.Gson; | |
import java.lang.reflect.Type; | |
import nl.qbusict.cupboard.Cupboard; | |
import nl.qbusict.cupboard.convert.FieldConverter; | |
import nl.qbusict.cupboard.convert.FieldConverterFactory; | |
public class GsonFieldConverterFactory implements FieldConverterFactory { | |
private Type mType; | |
private Gson mGson; | |
public GsonFieldConverterFactory(Gson gson, Type type) { | |
this.mGson = gson; | |
this.mType = type; | |
} | |
public GsonFieldConverterFactory(Type type) { | |
this.mType = type; | |
this.mGson = new Gson(); | |
} | |
@Override | |
public FieldConverter<?> create(Cupboard cupboard, Type type) { | |
if (type == mType) { | |
return new GsonFieldConverter(mGson, type); | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment