围绕多种方法的Content Provider事务

问题描述 投票:1回答:1

我需要围绕两个我没有创建但应该使用的方法创建一个Content Provider事务。方法addDog(Context, Dog) throws Exception在Dog表中添加一行。方法addToy(Context,Toy, long dogId) throws Exception在玩具表中添加一行。我想创建一个方法

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个回答
0
投票

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

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

如果所有其他方法都失败了,内容提供商可以为自定义操作实现call()

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

© www.soinside.com 2019 - 2024. All rights reserved.