Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save electrolobzik/d1694e01680320f0157c to your computer and use it in GitHub Desktop.
Save electrolobzik/d1694e01680320f0157c to your computer and use it in GitHub Desktop.
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]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment