Android: Better Performance with ContentProviderOperation
ContentProviders are one of Android's core building blocks. They represent a relational interface to data - either in databases or (cached) data from the cloud.
Sometimes you want to use them for multiple operations in a row. Like updating different sources and so on. In those cases you could call the respective ContentResolver
To create, delete or update a set of data in a batch like fashion you should use the class ContentProviderOperation
.
According to Android's documentation it is recommended to use ContentProviderOperations
- All operations execute within the same transaction - thus data integrity is assured
- This helps improve performance since starting, running and closing one transaction offers far better performance than opening and committing multiple transactions
- Finally using one batch operation instead of multiple isolated operations reduces the number of context switches between your app and the content provider you are using. This of course also helps to improve the performance of your app - and by using less cpu cycles also reduces the power consumption.
To create an object of ContentProviderOperation
you need to build it using the inner class ContentProviderOperation.Builder
. You obtain an object of the Builder class by calling one of the three static methods newInsert
, newUpdate
or newDelete
:
Method | Usage |
---|---|
newInsert | Create a Builder object suitable for an insert operation |
newUpdate | Create a Builder object suitable for an update operation |
newDelete | Create a Builder object suitable for a delete operation |
The Builder is an example of the Gang of Four Builder pattern. A Builder defines an interface for how to create objects. Concrete instances then create specific objects for the task at hand. In this case we have three different Builders for creating ContentProviderOperation
objects. These objects can be used to create, update or delete ContentProvider data sets.
Typically all steps necessary to create a ContentProviderOperation object are done in one round of method chaining. That's possible because all methods of the Builder
class return a Builder
object themself. The one exception is the build()
method, which instead returns the desired object: Our completely created ContentProviderOperation
object. So a typical chain might look like this:
ArrayList<ContentProviderOperation> ops =
new ArrayList<ContentProviderOperation>();
ops.add(
ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
.withValue(RawContacts.ACCOUNT_TYPE, "someAccountType")
.withValue(RawContacts.ACCOUNT_NAME, "someAccountName")
.withYieldAllowed(true)
.build());
Of course you could also use a ContentValues object as usual and use the withValues(values)
method instead.
The Builder class has among others these methods you can use to define which objects to delete or how to create or update an object:
Method | Usage |
---|---|
withSelection (String selection, String[] selectionArgs) | Specifies on which subset of the existing data set to operate. Only usable with ContentProviderOperation objects used to update or delete data |
withValue (String key, Object value) | Defines the desired value for one column. Only usable with ContentProviderOperation objects used to create or update data |
withValues (ContentValues values) | Defines the desired values for multiple columns. Only usable with ContentProviderOperation objects used to create or update data |
As you can see in the code sample I presented above you need an ArrayList
of ContentProviderOperation
objects. For every ContentProvider-CRUD method you have to use one ContentProviderOperation object and add it to this list. I will explain in a later blog post about the method withValueBackReference()
why it has to be an ArrayList and not say a LinkedList
.
The list is finally passed to the applyBatch()
method of the ContentResolver object:
try {
getContentResolver().
applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
// do s.th.
} catch (OperationApplicationException e) {
// do s.th.
}
That's all for now. I will explain two methods of the Builder class, that are not well documented, in separate follow up posts.
相關推薦
Android: Better Performance with ContentProviderOperation
ContentProviders are one of Android's core building blocks. They represent a relational interface to data - either in
解決Android Studio Conflict with dependency 'com.android.support:support-annotations' 問題
在Android Studio 建立新專案的時候,出現這個報錯: Error:Execution failed for task ':app:preDebugAndroidTestBuild'.> Conflict with dependency 'com.android.support:suppor
How To Create Android Swipe Views With Tabs
Android swipe views provide lateral navigation between sibling screens such as tabs with a horizontal finger gesture (a pattern sometimes known as horiz
Stream API performance with GraalVM
Better Java Streams performance with GraalVMThe functional Streams API introduced in Java 8 is a neat and efficient way to declaratively express programs t
Machine Learning: Balancing model performance with business goals
This post is designed to give some guidance for evaluating the use of machine learning to solve your business problem. As a data scientist, I am highly mot
Predicting School Performance with Census Income Data
Data VisualizationFirst, we can make a scatterplot with the location of every school using the library gmplot (pip install gmplot ).The plot shows that rat
Why working with a mobile development agency is better than with a freelancer?
Now it’s time to witness 3 short battlefields to find out who is going to be “just right” for your app idea: a bunch of mobile freelancers or a mobile agen
Better Conversations with Machines
Conversational ToolingThe opportunities in this section are applicable to conversational interfaces, whether those interfaces are voice or text.Portable Co
Better Exploration with Parameter Noise
Action Space Noise Parameter Space Noise Parameter noise helps algorithms more efficiently explore the range of actions available to
Crowdsourcing a better world with Oh Caption!
Crowdsourcing a better world with Oh Caption!You are volunteering your sight on Be My Eyes and on BeSpecular. When you get to help, it is wonderful. But, h
Assessing and Comparing Classifier Performance with ROC Curves
Tweet Share Share Google Plus The most commonly reported measure of classifier performance is ac
【Android】finished with non-zero exit value 2
異常提示 產生原因 解決辦法 注意 參考連結 異常提示 Error:Error converting bytecode to dex: Cause: com.android.dex.DexException: Multiple dex fil
Android application testing with the Android test framework
4.1. Android test projects Android organizes tests into separate Android test projects. Instead of Android components, an Android test application
編譯opencv的android版本(with ffmpeg)
1. 下載opencv的原始碼2. 在opencv的根目錄下新建目錄mybuild3. 進入mybuild目錄,執行命令:cmake \ -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=/usr/lo
Android Installation failed with message...It is possible that this issue is resolved by uninstalli
1.今天一個朋友問我這樣一個錯誤,資訊和圖如下:Installation failed with message...It is possible that this issue is resolved by uninstalling an existing version
android中圖型的陰影效果(shadow-effect-with-custom-shapes)
sim 狀態 odi bottom msu custom top ado cto 思路:在自己定義shape中添加一層或多層,並錯開。就可以顯示陰影效果。為添加立體感,button按下的時候,僅僅設置一層。我們能夠通過top, bottom, right 和 left 四
Android source code compile error: “Try increasing heap size with java option '-Xmx<size>'”
eap pre ted str tools courier odi xmx tier export JACK_SERVER_VM_ARGUMENTS="-Dfile.encoding=UTF-8 -XX:+TieredCompilation -Xmx4g" ./prebui
Android studio 導入項目錯誤Plugin with id‘com.XXXX
repos enc mage 圖片 gin build spa include ppc 1.打開AS ,展開項目列表打開方框中的build.gradle。2.添加 buildscript { repositories { mavenCentral(
Manifest merger failed with multiple errors, see logs -- Android Studio問題匯總
存在 clas andro 作用 alt tar strong AR multipl FAQ:> Manifest merger failed with multiple errors, see logs 解決: 此問題產生原因大概有三個 # 第一,清單文件
Android Studio 新建Andorid工程報錯: Conflict with dependency 'com.android.support:support-annotations'
bug 方法 andro erro failed resolv and div tails 新建Android工程報錯: Error:Execution failed for task ‘:app:preDebugAndroidTestBuild‘. > Confl