本文介绍了如何编组/解组ContentValues以将泛型类型插入ContentProvider?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个通用POJO放入ContentValues并将其在ContentProvider中解组.

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

我一直在扭动我的小脑袋:Parcelables,ContentValues,然后插入SQLite关于: http://njzk2.wordpress.com/2013/05/31/map-to-contentvalues-abusing-parcelable/

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

如何编写通用在Android的Sqlite中插入数据的代码

我一直试图通过ContentProvider将android.location.Location插入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 );

使用包裹填充值.

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

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

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

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)

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

Question 2)Is there some way I can unmarshal values first and then marshal it back into another ContentValues variable? maybe 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;
}

这篇关于如何编组/解组ContentValues以将泛型类型插入ContentProvider?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 03:31