Android - How can I pass data related to two tables to a the insert method of a Content Provider

随声附和 提交于 2019-11-28 11:47:35

You should use ContentProviderOperation. Since it's your ContentProvider you can assure that applyBatch() will execute all operations within a transaction. All standard content providers also ensure that that's the case.

See my blog post about ContentProviderOperation in general and my other post about how to use withBackReference() to access results of previous operations - which you need to access the orderId.

One important caveat: All ContentProviderOperations of one batch must use the same authority - but can use different URIs! In your case that should be no problem.

You can put all the data into a ContentValues and have a provider. You'll have to get a little creative with the order details.

Below psuedo code I create a key "DETAIL" on the fly with a integer then the item.

           ContentValues values = new ContentValues();
            values.put(ORDER_ID,orderid);

           for (int i = 0; i < items.size(); i++) {    
            values.put("DETAIL" + Integer.ToString(i),items.get(i));
            }

            Uri uri = context.getContentResolver().insert(
                    ORDER_URI, values);

Then in content provider you sort it out.

@Override
public Uri insert(Uri uri, ContentValues values) {

    int uriType = sURIMatcher.match(uri);
    SQLiteDatabase sqlDB = database.getWritableDatabase();
    long id = 0;
    switch (uriType) {
    case ORDER:
        // trim name and description
        trimNameDescriptions(values);
        try {
            id = sqlDB.insertOrThrow(ORDERS_TABLE,
                    null, values);
        Integer i =0;
        do (values.containsKey("DETAIL" + i.toString()){
        ContentValues v = new ContentValues();
        v.put("DETAIL",values.get("Detail" + i.toString()));
        v.put("ORDERID",id);
          //ACTUALLY CALL THE INSERT METHOD OF THE PROVIDER
        insert(DETAIL_URI,v);
         i+=1;
     }

You can design content provider to mirror your SQLite tables, and use insertOrder code same as above.

Just use insert of content providers for each table(uri), to perform similar operations as in your insertOrder method

Another option is to define your content provider URI to take combination of your Order and items , and implement the parsing yourself in the content provider before committing to underlying data model.

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