我想将一个通用的 POJO 放入 ContentValues 并在 ContentProvider 中解码。
我一直在绞尽脑汁:Parcelables、ContentValues 和插入 SQLite 关于: 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
我一直在尝试通过 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 变量吗?也许有 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;
}
关于android-contentprovider - 如何编码/解码 ContentValues 以将泛型类型插入 ContentProvider?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26307443/