Android: SQLite transactions when using ContentResolver

前端 未结 4 1944
一个人的身影
一个人的身影 2020-12-12 14:30

The goal: refresh database from XML data

The process:

  • Start transaction
  • Delete all existing rows from the ta
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-12 15:06

    You can get the implementation of the content provider object itself (if in the same process, hint: you can control the provider's process with multiprocess="true" or process="" http://developer.android.com/guide/topics/manifest/provider-element.html) using ContentProviderClient.getLocalContentProvider () which can be casted to your provider implementation which can provide extra functionality like a reset() that closes and deletes the database and you can also return a custom Transaction class instance with save() and close() methods.

    public class Transaction {
        protected Transaction (SQLiteDatabase database) {
            this.database = database;
            database.beginTransaction ();
        }
    
        public void save () {
            this.database.setTransactionSuccessful ();
        }
    
        public void close () {
            this.database.endTransaction ();
        }
    
        private SQLiteDatabase database;
    }
    
    public Transaction createTransaction () {
        return new Transaction (this.dbHelper.getWritableDatabase ());
    }
    

    Then:

    ContentProviderClient client = getContentResolver ().acquireContentProviderClient (Contract.authorityLocal);
    Transaction tx = ((LocalContentProvider) client.getLocalContentProvider ()).createTransaction ();
    

提交回复
热议问题