【问题标题】:Content Provider transaction around multiple methods围绕多种方法的内容提供者事务
【发布时间】:2018-01-02 20:38:55
【问题描述】:

我需要围绕我没有创建但应该使用的两种方法创建一个内容提供程序事务。方法addDog(Context, Dog) throws Exception 在 Dog 表中添加一行。方法 addToy(Context,Toy, long dogId) throws Exception 在 Toy 表中添加一行。我想创建一个方法

public void addDogAndToyAtomic(Context context, Dog dog, Toy toy) throws Exception{
  Transaction transaction = null;
  try{
    transaction = ContentProviders.getTransaction(...);//what is this?
    transaction.start();
    . . . //some more queries here and then
    long dogId = addDog(context, dog);
    addToy(context, toy, dogId);
    transaction.commit();
  }finally{
    if(null != transaction)transaction.close();
  }
}

如何在 Android 中创建此方法?我知道正在使用的提供程序的 CONTENT_URI,实际上我可以看到这两种方法的内部。这个问题的限制是我想使用现有的两种方法来创建第三个。

如果你好奇,addDog 看起来像这样:

public long addDog(Context context, Dog dog){
  Uri uri= context.getContentResolver().insert(
    PetContract.Dog.CONTENT_URI,
    dog.getContentValues()
  );
  return ContentUris.parseId(uri);
}

【问题讨论】:

    标签: android database sqlite transactions android-contentprovider


    【解决方案1】:

    内容提供者是一种抽象,不一定在带有事务的“真实”数据库之上实现。

    要一次执行多个独立操作,请使用applyBatch()。 (实际的实现可能会也可能不会使用单个事务。)

    如果一切都失败了,内容提供者可以为自定义操作实现call()

    但在一般情况下,如果没有内容提供者实现的合作,这是不可能的。

    【讨论】:

    • 我不拥有相关内容提供者。所以我不能向它添加方法。我对 applyBatch() 的理解是它适用于不相互依赖的操作。正如你在我的例子中看到的那样,我需要 dogId 来坚持 Toy。根据我的理解,applyBatch() 在这里不起作用——或者你有一个这样的相互依赖实现的简短例子吗?
    • 否;那是不可能的,
    猜你喜欢
    • 1970-01-01
    • 2015-10-24
    • 2014-06-08
    • 1970-01-01
    • 2020-03-28
    • 1970-01-01
    • 1970-01-01
    • 2012-04-05
    • 1970-01-01
    相关资源
    最近更新 更多