Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/396.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将java.util.HashMap转换为android.content.ContentValues?_Java_Android_Sqlite_Platform Independent_Database Independent - Fatal编程技术网

如何将java.util.HashMap转换为android.content.ContentValues?

如何将java.util.HashMap转换为android.content.ContentValues?,java,android,sqlite,platform-independent,database-independent,Java,Android,Sqlite,Platform Independent,Database Independent,有没有一种简单的方法可以将javaMap转换为android.content.ContentValues android.content.ContentValues在android数据库编程中用于将数据库行的数据保留为名称-值对 背景: 我尝试将现有android应用程序的业务逻辑移植到j2se swing应用程序 我的目标是拥有特定于android的代码 以及android独立代码,该代码进入一个单独的库中,可供android和swing gui使用 目前我正在分析 如果我必须用大量冗余代码

有没有一种简单的方法可以将java
Map
转换为
android.content.ContentValues

android.content.ContentValues
在android数据库编程中用于将数据库行的数据保留为名称-值对

背景:

我尝试将现有android应用程序的业务逻辑移植到j2se swing应用程序

我的目标是拥有特定于android的代码 以及android独立代码,该代码进入一个单独的库中,可供android和swing gui使用

目前我正在分析

  • 如果我必须用大量冗余代码实现一整套独立的Repository实现
  • 或者,如果存在可以在(j2se swing和android)存储库实现中使用的通用代码
存储库数据库代码依赖于使用android.content.ContentValues的数据库字段名-值对

我认为我的android独立版本可以使用
HashMap
insead of
ContentValues
并创建代码在两者之间进行转换

依赖安卓系统的版本如下所示

    // 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的代码
类AndroidTimeSliceCategoryRepository实现了ICategoryRepsitory{
公共长createTimeSliceCategory(最终时间片类别){
//从android独立层获取值
Map columnstobeinserted=TimeSliceCategorySql.asHashMap(category);
//>>>>这就是我被困的地方
ContentValues androidcolumnstobeinserted=DbUtils.asContentValues(columnstobeinserted);
final long newID=androidTimeSliceCategoryRepository.DB.getWritableDatabase()
.insert(TimeSliceCategorySql.TIME\u SLICE\u CATEGORY\u表,null,AndroidColumnStoBeInserted);
category.setRowId((int)newID);
返回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;
        }
    }
//公共jar中的android独立代码
类TimeSliceCategorySql{。。。。
/**将{@link….model.TimeSliceCategory}转换为{@link java.util.HashMap}*/
公共静态地图AshMap(最终时间片类别){
最终映射值=新HashMap();
value.put(TimeSliceCategorySql.COL_CATEGORY_NAME,
category.getCategoryName());
value.put(TimeSliceCategorySql.COL_说明,
category.getDescription());
//…更多价值观
返回值;
}
}
目前我被困在这里:

    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;
        }
    }
公共类AndroidDatabaseUtil{
/**从android独立的{@link java.util.Map}转换为依赖android的{@link android.content.ContentValues}*/
公共静态ContentValues到ContentValues(映射src){
ContentValues结果=新的ContentValues();
for(字符串名称:src.keySet()){
//这是不可能的,因为ContentValues不定义put(字符串名称、对象值)
result.put(name,src.get(name));
//使用此选项将丢失ContentValues.getAsLong()引发异常。
//result.put(name,src.get(name.toString());
}
src.entrySet()
返回结果;
}
}

您在地图中输入的值似乎是字符串

因此,您可以将地图的定义更改为

final Map<String, String> values = new HashMap<String, String>();

您可以使用
if
语句中的
instanceof
关键字对其进行过滤

例如:

if( src.get(name) instanceof String){
  // convert to string
}
您还可以使用对象中的
getClass
方法:

对象ob=src.get(名称)

然后

@Override
public Uri insert( final Uri uri, final ContentValues oldvalues ){
SQLiteDatabase db = GAELdatabase.getWritableDatabase();

Uri result = null;
Location loc = (Location)oldvalues.get("LOCATIONS");

ContentValues values = new ContentValues();

values.put("ALTITUDE", loc.getAltitude());//meters above sea level
values.put("LATITUDE", loc.getLatitude());
values.put("LONGITUDE", loc.getLongitude());

long rowID = db.insert( "MyTABLE_NAME", "", values);
db.close();
return result;
}

hashmap中的
对象的类型是什么?目前我有String、Integer、Long、Double和boolean。在我的示例中,我只使用String。在我的项目代码中,我还有整数、Long、Double和Boolean@k3b在这种情况下,可以使用
instanceof
来检查值的类型,并将其转换为整数、长、双精度等。。在将其放入ContentValues之前,使用相关的put方法。我决定将除blob-s之外的所有对象映射到字符串,因为我必须实现到另一个方向getInt(映射,键)的转换。这就是为什么我接受了这个答案,而不是@Kyle Emmanuelal虽然我已经实现了这个务实的方法,但我只是将接受的答案从这个改为@JDOaktown,它有一个通用的解决方案,可以解决我的问题。让我们看看对于涉及的每种类型,是否有比使用一个
if
更优雅的解决方案:String、Integer、Long、Double、BooleanI,在我决定实施“字符串表示法”解决方案之前,我已经看过这一方法;-)
  if(ob instanceof ob.getClass()){
   // convert to type
  }
Location loc = mLocationClient.getLastLocation();
HashMap hm = new HashMap();
hm.put("LOCATIONS", loc);
Parcel myParcel = Parcel.obtain();    
myParcel.writeMap(hm);
myParcel.setDataPosition(0);

ContentValues values = ContentValues.CREATOR.createFromParcel(myParcel);

getContentResolver().insert(MyDumbUri, values);
@Override
public Uri insert( final Uri uri, final ContentValues oldvalues ){
SQLiteDatabase db = GAELdatabase.getWritableDatabase();

Uri result = null;
Location loc = (Location)oldvalues.get("LOCATIONS");

ContentValues values = new ContentValues();

values.put("ALTITUDE", loc.getAltitude());//meters above sea level
values.put("LATITUDE", loc.getLatitude());
values.put("LONGITUDE", loc.getLongitude());

long rowID = db.insert( "MyTABLE_NAME", "", values);
db.close();
return result;
}