android-contentprovider - 如何编码/解码 ContentValues 以将泛型类型插入 ContentProvider?

标签 android-contentprovider parcelable parcel

我想将一个通用的 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/

相关文章:

Android:使用 android.provider.Telephony.Sms.Conversations

android - 我可以直接在 ContentProvider 的 open ParcelFileDescriptor openFile() 中传递我的 InputStream 吗?

android - 我可以将自定义对象发送到 Android Wear 吗?

android - 在 Android 中使用 Serializable 不好吗?

android - 仅在牛轧糖上出现 TransactionTooLargeException

Kotlin 中的 Android Parcelable : CREATOR not found on Parcelable data class

内容的 Widget RemoteViewsFactory 中的 Android 权限拒绝

android - Parcelable vs 从数据库读取的效率

android嵌套对象打包

java - 需要共享 ContentProvider 代码但唯一的内容权限