有没有一种简单的方法可以从 java 转换Map<String,Object>
为android.content.ContentValues
.
android.content.ContentValues
在android数据库编程中用于将数据库行的数据保存为名称-值对。
背景:
我尝试将现有 android 应用程序的业务逻辑移植到 j2se-swing-app
我的目标是让 android 特定代码和 android 独立代码进入一个单独的库,供 android 和 swing-gui 使用。
目前我正在分析
- 如果我必须使用大量冗余代码实现一组完整的独立存储库实现
- 或者如果有可以在(j2se-swing-和android-)存储库-实现中使用的通用代码。
Repository-Database-Code 依赖于使用android.content.ContentValues
.
我认为我的 android 独立版本可以使用HashMap<String,Object>
inseadContentValues
并创建代码在两者之间进行转换。
android依赖版本看起来像这样
// android dependant code in android-app
class AndroidTimeSliceCategoryRepsitory implements ICategoryRepsitory {
public long createTimeSliceCategory(final TimeSliceCategory category) {
// get values from android independant layer
Map<String, Object> columsToBeInserted = TimeSliceCategorySql.asHashMap(category);
// >>>> this is where i am stuck
ContentValues androidColumsToBeInserted = DbUtils.asContentValues(columsToBeInserted);
final long newID = AndroidTimeSliceCategoryRepsitory.DB.getWritableDatabase()
.insert(TimeSliceCategorySql.TIME_SLICE_CATEGORY_TABLE, null, androidColumsToBeInserted);
category.setRowId((int) newID);
return newID;
}
}
这是android独立部分:
// android independant code in common jar
class TimeSliceCategorySql {....
/** converts {@link ....model.TimeSliceCategory} to {@link java.util.HashMap} */
public static Map<String, Object> asHashMap(final TimeSliceCategory category) {
final Map<String, Object> values = new HashMap<String, Object>();
values.put(TimeSliceCategorySql.COL_CATEGORY_NAME,
category.getCategoryName());
values.put(TimeSliceCategorySql.COL_DESCRIPTION,
category.getDescription());
// ... more values
return values;
}
}
目前我被困在这里:
public class AndroidDatabaseUtil {
/** converts from android independeant {@link java.util.Map} to android dependent {@link android.content.ContentValues} */
public static ContentValues toContentValues(Map<String, Object> src) {
ContentValues result = new ContentValues();
for (String name : src.keySet()) {
// this is not possible because ContentValues does not define put(String name, Object value)
result.put(name, src.get(name));
// using this would loose ContentValues.getAsLong() throw exception.
// result.put(name, src.get(name).toString());
}
src.entrySet()
return result;
}
}