How to convert from java.util.HashMap to android.content.ContentValues?

Is there an easy way to convert from java Map<String,Object>to android.content.ContentValues?

android.content.ContentValues used in Android database programming to store database row data as name-value pairs.

Background:

I am trying to migrate the business logic of an existing Android application to j2se-swing-app

I have a special code for Android and an android independent code, which is included in a separate lib that can be used by both android and swing-gui.

I am currently analyzing

  • if I need to implement a complete separate set of repositories with lots of redundant code
  • or if there is generic code that can be used in both (j2se-swing- and android-) Implementation repositories.

Repository-Database-Code uses the name-database pairs in which it is used android.content.ContentValues.

I thought that the Android version without an android could use HashMap<String,Object>insead of ContentValuesand create code to convert between them.

The version dependent on android will look like this:

    // 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;
        }
    }

This is an independent part of 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;
        }
    }

I'm currently stuck here:

    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;
        }
    }
+4
source share
3 answers

How do marshal / unmarshal ContentValues ​​insert a generic type into a ContentProvider?

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);

and then

@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;
}
+3
source

It looks like the values ​​you entered on your map are strings.

Therefore, you can change the map definition to

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

ContentValues:

result.put(name, src.get(name));
+2

You can filter it using the keyword instanceofin the instructions if.

Example:

if( src.get(name) instanceof String){
  // convert to string
}

You can also use the method getClassfor the object:

Object ob = src.get (name);

  if(ob instanceof ob.getClass()){
   // convert to type
  }
+1
source

All Articles