1

I need to create a Content Provider transaction around two methods that I didn't create but should use. Method addDog(Context, Dog) throws Exception adds a row in the Dog table. Method addToy(Context,Toy, long dogId) throws Exception adds a row in the Toy table. I would like to create a method

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

How do I create this method in Android? I know the CONTENT_URI for the provider being used, in fact I can see inside the two methods. The constraint in this question is that I want to use the existing two methods to create this third.

In case you are curious, addDog looks like this:

public long addDog(Context context, Dog dog){
  Uri uri= context.getContentResolver().insert(
    PetContract.Dog.CONTENT_URI,
    dog.getContentValues()
  );
  return ContentUris.parseId(uri);
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
salyela
  • 1,325
  • 3
  • 14
  • 26

1 Answers1

0

Content providers are an abstraction that is not necessarily implemented on top of a 'real' database with transactions.

To do multiple independent operations at once, use applyBatch(). (The actual implementation might or might not use a single transaction.)

If all else fails, a content provider can implement call() for custom actions.

But in the general case, without the cooperation of the content provider implementation, this is not possible.

CL.
  • 173,858
  • 17
  • 217
  • 259
  • I don't own the Content Provider in question. So I cannot add methods to it. My understanding of applyBatch() is that it works on operations that aren't inter-dependent. As you can see in my case, I need dogId in order to persist Toy. applyBatch() per my understanding won't work here -- or do you have a short example of such inter-dependence implementation? – salyela Jan 03 '18 at 17:18
  • No; it is not possible then, – CL. Jan 03 '18 at 18:20