Skip to content

Instantly share code, notes, and snippets.

@hvisser
Last active February 20, 2017 00:40
Show Gist options
  • Save hvisser/9394716 to your computer and use it in GitHub Desktop.
Save hvisser/9394716 to your computer and use it in GitHub Desktop.
Custom field converter example for Cupboard
package nl.qbusict.cupboard;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.test.AndroidTestCase;
import nl.qbusict.cupboard.convert.EntityConverter.ColumnType;
import nl.qbusict.cupboard.convert.FieldConverter;
public class TestStringArrayConverter extends AndroidTestCase {
public static class TestEntity {
public Long _id;
public String[] myStringArray;
}
public void testStringArrayConverter() {
// Note that this converter does not handle escaping commas that are also used
// as a separator
FieldConverter<String[]> converter = new FieldConverter<String[]>() {
@Override
public String[] fromCursorValue(Cursor cursor, int columnIndex) {
return cursor.getString(columnIndex).split(",");
}
@Override
public void toContentValue(String[] value, String key, ContentValues values) {
if (value.length > 0) {
StringBuilder sb = new StringBuilder(1024);
for (String s : value) {
sb.append(s);
sb.append(",");
}
// strip off trailing comma
sb.setLength(sb.length() - 1);
values.put(key, sb.toString());
} else {
values.put(key, "");
}
}
@Override
public ColumnType getColumnType() {
return ColumnType.TEXT;
}
};
Cupboard cb = new CupboardBuilder().
registerFieldConverter(String[].class, converter).
build();
cb.register(TestEntity.class);
TestEntity entity = new TestEntity();
entity.myStringArray = new String[] {"hello", "world"};
ContentValues values = cb.withEntity(TestEntity.class).toContentValues(entity);
assertEquals("hello,world", values.getAsString("myStringArray"));
MatrixCursor cursor = new MatrixCursor(new String[] {"myStringArray"});
cursor.addRow(new Object[] {"world,hello"});
cursor.moveToFirst();
entity = cb.withCursor(cursor).get(TestEntity.class);
assertEquals(2, entity.myStringArray.length);
assertEquals("world", entity.myStringArray[0]);
assertEquals("hello", entity.myStringArray[1]);
}
}
@dbachelder
Copy link

using guava here would be really slick too..

public void toContentValue(String[] value, String key, ContentValues values) {
  values.put(key, value == null ? "" : Joiner.on(',').join(value));
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment