如何编组/解组 ContentValues 以将泛型类型插入 ContentProvider?

2024-02-09

我想将通用 POJO 放入 ContentValues 中并在 ContentProvider 中解组它。

我一直在绞尽脑汁地思考:Parcelables、ContentValues 和插入 SQLite 关于:http://njzk2.wordpress.com/2013/05/31/map-to-contentvalues-abusing-parcelable/ http://njzk2.wordpress.com/2013/05/31/map-to-contentvalues-abusing-parcelable/

如何编写在android的Sqlite中插入数据的通用代码 https://stackoverflow.com/questions/23244834/how-to-write-a-common-code-for-inserting-data-in-androids-sqlite

我一直在尝试通过 ContentProvider 将 android.location.Location 插入到 SQLite 中:

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

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

用地块填充值。

问题1) 这是我的 ContentProvider.insert 方法:

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

这失败了,因为 db.insert() 没有解组值(我相信) 插入 android.database.sqlite.SQLiteException 时出错:INSERT INTO myTABLE_NAME() VALUES (NULL)

问题2) 有什么方法可以先解组值,然后将其编组回另一个 ContentValues 变量吗?也许w/ getKey()???


这有效:

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

进而

@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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何编组/解组 ContentValues 以将泛型类型插入 ContentProvider? 的相关文章

随机推荐