How to marshal/unmarshal ContentValues to insert generic type into ContentProvider?

大城市里の小女人 提交于 2019-12-07 12:12:17

问题


I want to put a generic POJO into ContentValues and unmarshall it within the ContentProvider.

I've been wracking my tiny brain re: Parcelables, ContentValues, and inserting into SQLite Regarding: http://njzk2.wordpress.com/2013/05/31/map-to-contentvalues-abusing-parcelable/

How to write a common code for inserting data in android's Sqlite

I've been trying to insert a android.location.Location into SQLite via ContentProvider:

Location loc = mLocationClient.getLastLocation();
myParcel = android.os.Parcel.obtain();
loc.writeToParcel(myParcel, 0);

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

to populate values w/ parcel.

Question 1) Here is my ContentProvider.insert method:

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

//db.insert() doesn’t unmarshal the values??
db.insert(  myTABLE_NAME, “”, values);

Uri result = null;
db.close();
return result;
}

this fails because the db.insert() doesn’t unmarshal the values (i believe) Error inserting android.database.sqlite.SQLiteException: INSERT INTO myTABLE_NAME() VALUES (NULL)

Question 2) Is there some way I can unmarshal values first and then marshal it back into another ContentValues variable? maybe w/ getKey()???


回答1:


This works:

HashMap hm = new HashMap();
Location loc = mLocationClient.getLastLocation();
hm.put("LOCATIONS", loc);

android.os.Parcel myParcel = android.os.Parcel.obtain();    
myParcel.writeMap(hm);
myParcel.setDataPosition(0);

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

getContentResolver().insert(MyUri, 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;
}


来源:https://stackoverflow.com/questions/26307443/how-to-marshal-unmarshal-contentvalues-to-insert-generic-type-into-contentprovid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!