├── settings.gradle ├── library ├── src │ ├── test │ │ ├── resources │ │ │ └── mockito-extensions │ │ │ │ └── org.mockito.plugins.MockMaker │ │ └── java │ │ │ └── com │ │ │ └── doctoror │ │ │ └── rxcursorloader │ │ │ └── RxCursorLoaderTest.java │ └── main │ │ ├── AndroidManifest.xml │ │ └── java │ │ └── com │ │ └── doctoror │ │ └── rxcursorloader │ │ ├── QueryReturnedNullException.java │ │ ├── RxCursorLoaderSingleFactory.java │ │ ├── RxCursorLoaderFlowableFactory.java │ │ └── RxCursorLoader.java ├── gradle.properties ├── proguard-rules.pro ├── build.gradle └── gradle-mvn-push.gradle ├── demo ├── src │ └── main │ │ ├── res │ │ ├── mipmap-hdpi │ │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ │ └── ic_launcher.png │ │ ├── mipmap-xxxhdpi │ │ │ └── ic_launcher.png │ │ ├── values │ │ │ ├── styles.xml │ │ │ ├── colors.xml │ │ │ ├── dimens.xml │ │ │ └── strings.xml │ │ ├── values-v11 │ │ │ └── styles.xml │ │ ├── values-v21 │ │ │ └── styles.xml │ │ ├── values-w820dp │ │ │ └── dimens.xml │ │ └── layout │ │ │ ├── list_item_two_line.xml │ │ │ └── activity_demo.xml │ │ ├── java │ │ └── com │ │ │ └── doctoror │ │ │ └── rxcursorloader │ │ │ └── demo │ │ │ ├── DemoApp.java │ │ │ ├── ArtistsQuery.java │ │ │ ├── DemoContentProvider.java │ │ │ ├── ArtistsCursorAdapter.java │ │ │ └── DemoActivity.java │ │ └── AndroidManifest.xml ├── proguard-rules.pro └── build.gradle ├── .gitignore ├── CHANGELOG.md ├── gradle.properties ├── dependencies.gradle ├── README.md └── LICENSE /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':demo', ':library' 2 | -------------------------------------------------------------------------------- /library/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker: -------------------------------------------------------------------------------- 1 | mock-maker-inline 2 | -------------------------------------------------------------------------------- /library/gradle.properties: -------------------------------------------------------------------------------- 1 | POM_NAME=RxCursorLoader 2 | POM_ARTIFACT_ID=library 3 | POM_PACKAGING=aar 4 | -------------------------------------------------------------------------------- /demo/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Doctoror/RxCursorLoader/HEAD/demo/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /demo/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Doctoror/RxCursorLoader/HEAD/demo/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /demo/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Doctoror/RxCursorLoader/HEAD/demo/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /demo/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Doctoror/RxCursorLoader/HEAD/demo/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /demo/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Doctoror/RxCursorLoader/HEAD/demo/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /library/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /demo/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /demo/src/main/res/values-v11/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /demo/src/main/res/values-v21/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /demo/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | #FF4081 6 | 7 | -------------------------------------------------------------------------------- /demo/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16dp 4 | 16dp 5 | 6 | -------------------------------------------------------------------------------- /demo/src/main/res/values-w820dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 64dp 6 | 7 | -------------------------------------------------------------------------------- /demo/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | RxCursorLoader Demo 3 | 4 | Permission denied 5 | No artists found 6 | 7 | 8 | %1$d album 9 | %1$d albums 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | #Android Studio files 2 | *.iml 3 | .gradle 4 | gradle 5 | gradlew* 6 | .idea 7 | .DS_Store 8 | build 9 | keystore 10 | *.keystore 11 | 12 | #built application files 13 | *.apk 14 | *.ap_ 15 | 16 | # files for the dex VM 17 | *.dex 18 | 19 | # Java class files 20 | *.class 21 | 22 | # generated files 23 | proguard 24 | bin 25 | gen 26 | 27 | # Local configuration file (sdk path, etc) 28 | local.properties 29 | 30 | /captures 31 | .externalNativeBuild 32 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # 2.1.1 2 | - Added `observable` factory method to be able to use Observables again; 3 | - Removed `HandlerThread` usage in favor of main-threaded `ContentObserver` `Handler`; 4 | - Decreased `synchronize` scope. 5 | 6 | # 2.1.0 7 | - Fixed single not setting `QueryReturnedNullException` when provider returns null; 8 | - Added `flowable` method which also accepts `Scheduler` and `BackpressureStrategy`; 9 | - `create` method is deprecated in favor of `flowable`. 10 | 11 | # 2.0.2 12 | 13 | - Downgrade to Java 7 ([issue #3](/../../issues/3)) 14 | -------------------------------------------------------------------------------- /demo/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /home/doctor/android-sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /library/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /home/doctor/android-sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /demo/src/main/java/com/doctoror/rxcursorloader/demo/DemoApp.java: -------------------------------------------------------------------------------- 1 | package com.doctoror.rxcursorloader.demo; 2 | 3 | import android.app.Application; 4 | import android.os.StrictMode; 5 | 6 | /** 7 | * Created by Yaroslav Mytkalyk on 10.01.17. 8 | */ 9 | public final class DemoApp extends Application { 10 | 11 | @Override 12 | public void onCreate() { 13 | super.onCreate(); 14 | StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() 15 | .detectAll() 16 | .penaltyLog() 17 | .build()); 18 | 19 | StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() 20 | .detectAll() 21 | .penaltyLog() 22 | .build()); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /library/src/main/java/com/doctoror/rxcursorloader/QueryReturnedNullException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2017 Yaroslav Mytkalyk 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.doctoror.rxcursorloader; 17 | 18 | /** 19 | * Is thrown when a query returns null 20 | */ 21 | public class QueryReturnedNullException extends Exception { 22 | 23 | public QueryReturnedNullException() { 24 | 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /demo/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /demo/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | 5 | def globalConfiguration = rootProject.extensions.getByName("ext") 6 | 7 | compileSdkVersion globalConfiguration["androidCompileSdkVersion"] 8 | buildToolsVersion globalConfiguration["androidBuildToolsVersion"] 9 | 10 | defaultConfig { 11 | applicationId "com.doctoror.cursorloaderobservable.demo" 12 | 13 | minSdkVersion 14 14 | targetSdkVersion globalConfiguration["androidTargetSdkVersion"] 15 | 16 | versionCode globalConfiguration["androidVersionCode"] 17 | versionName globalConfiguration["androidVersionName"] 18 | } 19 | 20 | compileOptions { 21 | sourceCompatibility JavaVersion.VERSION_1_8 22 | targetCompatibility JavaVersion.VERSION_1_8 23 | } 24 | 25 | buildTypes { 26 | release { 27 | minifyEnabled false 28 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 29 | } 30 | } 31 | } 32 | 33 | dependencies { 34 | def d = rootProject.ext.demoDependencies 35 | 36 | implementation project(':library') 37 | implementation d.annotations 38 | implementation d.cursorAdapter 39 | implementation d.rxJava 40 | implementation d.rxAndroid 41 | } 42 | -------------------------------------------------------------------------------- /library/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | 3 | android { 4 | 5 | def globalConfiguration = rootProject.extensions.getByName("ext") 6 | 7 | compileSdkVersion globalConfiguration["androidCompileSdkVersion"] 8 | buildToolsVersion globalConfiguration["androidBuildToolsVersion"] 9 | 10 | defaultConfig { 11 | minSdkVersion globalConfiguration["androidMinSdkVersion"] 12 | targetSdkVersion globalConfiguration["androidTargetSdkVersion"] 13 | 14 | versionCode globalConfiguration["androidVersionCode"] 15 | versionName globalConfiguration["androidVersionName"] 16 | } 17 | 18 | lintOptions { 19 | checkAllWarnings true 20 | } 21 | 22 | buildTypes { 23 | release { 24 | } 25 | } 26 | 27 | configurations { 28 | javadocDeps 29 | } 30 | } 31 | 32 | dependencies { 33 | def d = rootProject.ext.libraryDependencies 34 | def td = rootProject.ext.libraryTestDependencies 35 | 36 | testImplementation td.junit 37 | testImplementation td.mockito 38 | testImplementation td.robolectric 39 | 40 | javadocDeps d.annotations 41 | javadocDeps d.rxJava 42 | 43 | implementation d.annotations 44 | implementation d.rxJava 45 | } 46 | 47 | apply from: './gradle-mvn-push.gradle' 48 | -------------------------------------------------------------------------------- /demo/src/main/res/layout/list_item_two_line.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 23 | 24 | 37 | 38 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | org.gradle.jvmargs=-Xmx1536m 13 | 14 | # When configured, Gradle will run in incubating parallel mode. 15 | # This option should only be used with decoupled projects. More details, visit 16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 17 | # org.gradle.parallel=true 18 | 19 | VERSION_NAME=2.1.2 20 | VERSION_CODE=19 21 | GROUP=com.github.doctoror.rxcursorloader 22 | 23 | POM_DESCRIPTION=An RX replacement for android.content.CursorLoader 24 | POM_URL=https://github.com/Doctoror/RxCursorLoader 25 | POM_SCM_URL=https://github.com/Doctoror/RxCursorLoader 26 | POM_SCM_CONNECTION=scm:git@github.com:Doctoror/RxCursorLoader.git 27 | POM_SCM_DEV_CONNECTION=scm:git@github.com:Doctoror/RxCursorLoader.git 28 | POM_LICENCE_NAME=The Apache Software License, Version 2.0 29 | POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt 30 | POM_LICENCE_DIST=repo 31 | POM_DEVELOPER_ID=Doctoror 32 | POM_DEVELOPER_NAME=Yaroslav Mytkalyk 33 | android.useAndroidX=true 34 | -------------------------------------------------------------------------------- /dependencies.gradle: -------------------------------------------------------------------------------- 1 | allprojects { 2 | repositories { 3 | jcenter() 4 | maven { url 'https://maven.google.com' } 5 | } 6 | } 7 | 8 | ext { 9 | //Android 10 | androidBuildToolsVersion = "28.0.3" 11 | androidMinSdkVersion = 9 12 | androidTargetSdkVersion = 28 13 | androidCompileSdkVersion = 28 14 | 15 | //Libraries 16 | androidXAnnotationsVersion = '1.0.2' 17 | androidXCursorAdapterVersion = '1.0.0' 18 | rxJavaVersion = '2.2.8' 19 | rxAndroidVersion = '2.1.1' 20 | 21 | //Testing 22 | jUnitVersion = '4.12' 23 | mockitoVersion = '2.25.1' 24 | robolectricVersion = '4.2.1' 25 | 26 | demoDependencies = [ 27 | annotations : "androidx.annotation:annotation:$androidXAnnotationsVersion", 28 | cursorAdapter: "androidx.cursoradapter:cursoradapter:$androidXCursorAdapterVersion", 29 | rxJava : "io.reactivex.rxjava2:rxjava:$rxJavaVersion", 30 | rxAndroid : "io.reactivex.rxjava2:rxandroid:$rxAndroidVersion" 31 | ] 32 | 33 | libraryDependencies = [ 34 | annotations: "androidx.annotation:annotation:$androidXAnnotationsVersion", 35 | rxJava : "io.reactivex.rxjava2:rxjava:$rxJavaVersion" 36 | ] 37 | 38 | libraryTestDependencies = [ 39 | junit : "junit:junit:$jUnitVersion", 40 | mockito : "org.mockito:mockito-core:$mockitoVersion", 41 | robolectric: "org.robolectric:robolectric:$robolectricVersion" 42 | ] 43 | } 44 | -------------------------------------------------------------------------------- /demo/src/main/res/layout/activity_demo.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 14 | 15 | 24 | 25 | 33 | 34 | 38 | 39 | -------------------------------------------------------------------------------- /demo/src/main/java/com/doctoror/rxcursorloader/demo/ArtistsQuery.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 Yaroslav Mytkalyk 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.doctoror.rxcursorloader.demo; 17 | 18 | import com.doctoror.rxcursorloader.RxCursorLoader; 19 | 20 | import android.net.Uri; 21 | import android.provider.MediaStore; 22 | 23 | /** 24 | * Created by Yaroslav Mytkalyk on 17.10.16. 25 | */ 26 | final class ArtistsQuery { 27 | 28 | private ArtistsQuery() { 29 | throw new UnsupportedOperationException(); 30 | } 31 | 32 | private static final Uri URI = new Uri.Builder().scheme("content") 33 | .authority(DemoContentProvider.AUTHORITY).build(); 34 | 35 | static final String[] COLUMNS = new String[]{ 36 | MediaStore.Audio.Artists._ID, 37 | MediaStore.Audio.Artists.NUMBER_OF_ALBUMS, 38 | MediaStore.Audio.Artists.ARTIST 39 | }; 40 | 41 | static final int COLUMN_NUMBER_OF_ALBUMS = 1; 42 | static final int COLUMN_ARTIST = 2; 43 | 44 | static final RxCursorLoader.Query QUERY = new RxCursorLoader.Query.Builder() 45 | .setContentUri(URI) 46 | .setProjection(COLUMNS) 47 | .setSortOrder(MediaStore.Audio.Artists.ARTIST) 48 | .create(); 49 | } 50 | -------------------------------------------------------------------------------- /demo/src/main/java/com/doctoror/rxcursorloader/demo/DemoContentProvider.java: -------------------------------------------------------------------------------- 1 | package com.doctoror.rxcursorloader.demo; 2 | 3 | import android.content.ContentProvider; 4 | import android.content.ContentValues; 5 | import android.database.Cursor; 6 | import android.database.MatrixCursor; 7 | import android.net.Uri; 8 | 9 | import androidx.annotation.NonNull; 10 | import androidx.annotation.Nullable; 11 | 12 | public final class DemoContentProvider extends ContentProvider { 13 | 14 | public static final String AUTHORITY = "com.doctoror.rxcursorloader.demo.provider"; 15 | 16 | @Override 17 | public boolean onCreate() { 18 | return true; 19 | } 20 | 21 | @Override 22 | public Cursor query( 23 | @NonNull Uri uri, 24 | @Nullable String[] projection, 25 | @Nullable String selection, 26 | @Nullable String[] selectionArgs, 27 | @Nullable String sortOrder) { 28 | final MatrixCursor demoResult = new MatrixCursor(ArtistsQuery.COLUMNS); 29 | demoResult.addRow(new String[]{ 30 | "1", 31 | "3", 32 | "Darkspace" 33 | }); 34 | demoResult.addRow(new String[]{ 35 | "2", 36 | "2", 37 | "Paysage d'Hiver" 38 | }); 39 | demoResult.addRow(new String[]{ 40 | "3", 41 | "6", 42 | "KMFDM" 43 | }); 44 | demoResult.addRow(new String[]{ 45 | "4", 46 | "4", 47 | "Mechina" 48 | }); 49 | return demoResult; 50 | } 51 | 52 | @Override 53 | public String getType(@NonNull Uri uri) { 54 | return "demo"; 55 | } 56 | 57 | @Override 58 | public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) { 59 | throw new UnsupportedOperationException(); 60 | } 61 | 62 | @Override 63 | public int delete(@NonNull Uri uri, @Nullable String selection, 64 | @Nullable String[] selectionArgs) { 65 | throw new UnsupportedOperationException(); 66 | } 67 | 68 | @Override 69 | public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, 70 | @Nullable String[] selectionArgs) { 71 | throw new UnsupportedOperationException(); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /demo/src/main/java/com/doctoror/rxcursorloader/demo/ArtistsCursorAdapter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 Yaroslav Mytkalyk 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.doctoror.rxcursorloader.demo; 17 | 18 | import android.content.Context; 19 | import android.database.Cursor; 20 | import android.view.LayoutInflater; 21 | import android.view.View; 22 | import android.view.ViewGroup; 23 | import android.widget.TextView; 24 | 25 | import androidx.annotation.NonNull; 26 | import androidx.cursoradapter.widget.CursorAdapter; 27 | 28 | /** 29 | * Created by Yaroslav Mytkalyk on 31.10.16. 30 | */ 31 | 32 | public final class ArtistsCursorAdapter extends CursorAdapter { 33 | 34 | private final LayoutInflater mInflater; 35 | 36 | public ArtistsCursorAdapter(final Context context, final Cursor c) { 37 | super(context, c, FLAG_REGISTER_CONTENT_OBSERVER); 38 | mInflater = LayoutInflater.from(context); 39 | } 40 | 41 | @Override 42 | public View newView(final Context context, final Cursor cursor, final ViewGroup viewGroup) { 43 | final View view = mInflater.inflate(R.layout.list_item_two_line, viewGroup, false); 44 | view.setTag(new ViewHolder(view)); 45 | return view; 46 | } 47 | 48 | @Override 49 | public void bindView(final View view, final Context context, final Cursor cursor) { 50 | final ViewHolder vh = (ViewHolder) view.getTag(); 51 | vh.text1.setText(cursor.getString(ArtistsQuery.COLUMN_ARTIST)); 52 | 53 | final int albumsCount = cursor.getInt(ArtistsQuery.COLUMN_NUMBER_OF_ALBUMS); 54 | vh.text2.setText(context.getResources().getQuantityString(R.plurals.d_albums, 55 | albumsCount, albumsCount)); 56 | } 57 | 58 | private static final class ViewHolder { 59 | 60 | TextView text1; 61 | TextView text2; 62 | 63 | ViewHolder(@NonNull final View view) { 64 | text1 = (TextView) view.findViewById(android.R.id.text1); 65 | text2 = (TextView) view.findViewById(android.R.id.text2); 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /library/src/main/java/com/doctoror/rxcursorloader/RxCursorLoaderSingleFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018 Yaroslav Mytkalyk 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.doctoror.rxcursorloader; 17 | 18 | import android.content.ContentResolver; 19 | import android.database.Cursor; 20 | import android.util.Log; 21 | 22 | import androidx.annotation.NonNull; 23 | import io.reactivex.Single; 24 | import io.reactivex.SingleEmitter; 25 | import io.reactivex.SingleOnSubscribe; 26 | 27 | import static com.doctoror.rxcursorloader.RxCursorLoader.TAG; 28 | import static com.doctoror.rxcursorloader.RxCursorLoader.isDebugLoggingEnabled; 29 | 30 | final class RxCursorLoaderSingleFactory { 31 | 32 | @NonNull 33 | static Single single( 34 | @NonNull final ContentResolver resolver, 35 | @NonNull final RxCursorLoader.Query query) { 36 | //noinspection ConstantConditions 37 | if (resolver == null) { 38 | throw new NullPointerException("ContentResolver param must not be null"); 39 | } 40 | //noinspection ConstantConditions 41 | if (query == null) { 42 | throw new NullPointerException("Params param must not be null"); 43 | } 44 | 45 | return Single.create(new CursorLoaderOnSubscribeSingle(resolver, query)); 46 | } 47 | 48 | private static final class CursorLoaderOnSubscribeSingle 49 | implements SingleOnSubscribe { 50 | 51 | @NonNull 52 | private final ContentResolver mContentResolver; 53 | 54 | @NonNull 55 | private final RxCursorLoader.Query mQuery; 56 | 57 | CursorLoaderOnSubscribeSingle( 58 | @NonNull final ContentResolver resolver, 59 | @NonNull final RxCursorLoader.Query query) { 60 | mContentResolver = resolver; 61 | mQuery = query; 62 | } 63 | 64 | @Override 65 | public void subscribe(final SingleEmitter emitter) { 66 | if (isDebugLoggingEnabled()) { 67 | Log.d(TAG, mQuery.toString()); 68 | } 69 | 70 | final Cursor c = mContentResolver.query( 71 | mQuery.contentUri, 72 | mQuery.projection, 73 | mQuery.selection, 74 | mQuery.selectionArgs, 75 | mQuery.sortOrder); 76 | 77 | if (c != null) { 78 | emitter.onSuccess(c); 79 | } else { 80 | emitter.onError(new QueryReturnedNullException()); 81 | } 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | 3 | An RX replacement for [android.content.CursorLoader](https://developer.android.com/reference/android/content/CursorLoader.html) 4 | 5 | Min API level 9 6 | 7 | ## Setup 8 | 9 | [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.github.doctoror.rxcursorloader/library/badge.png?style=flat)](https://maven-badges.herokuapp.com/maven-central/com.github.doctoror.rxcursorloader/library) 10 | 11 | For RxJava 2 12 | ```groovy 13 | compile 'com.github.doctoror.rxcursorloader:library:[version]' 14 | ``` 15 | 16 | If you need RxJava 1, you can use the old version 17 | ```groovy 18 | compile 'com.github.doctoror.rxcursorloader:library:1.1.5' 19 | ``` 20 | 21 | ## Usage 22 | 23 | Create a Query using Query.Builder. The required parameter is only a content URI. 24 | ```java 25 | final RxCursorLoader.Query query = new RxCursorLoader.Query.Builder() 26 | .setContentUri(MediaStore.Audio.Media.INTERNAL_CONTENT_URI) 27 | .setProjection(new String[]{MediaStore.Audio.Media._ID}) 28 | .setSortOrder(MediaStore.Audio.Artists.ARTIST) 29 | .setSelection(MediaStore.Audio.Artists.ARTIST + "=?") 30 | .setSelectionArgs(new String[] {"Oh Long Johnson"}) 31 | .create(); 32 | ``` 33 | 34 | Thare are two cases covered by this library. 35 | 36 | 1) You want to load the Cursor once 37 | 38 | ```java 39 | RxCursorLoader.single(getContentResolver(), query) 40 | .subscribeOn(Schedulers.io()) 41 | .observeOn(AndroidSchedulers.mainThread()) 42 | .subscribe(this::handleAndCloseCursor); 43 | ``` 44 | 2) You want to reload a Cursor every time the content under URI changes, just like CursorLoader does. 45 | Note that unlike CursorLoader, this does not close the Cursor for you, so make sure to close old cursor once onNext() is called. 46 | 47 | ```java 48 | mCursorDisposable = RxCursorLoader 49 | .flowable(getContentResolver(), params, Schedulers.io(), BackpressureStrategy.LATEST) 50 | .observeOn(AndroidSchedulers.mainThread()) 51 | .subscribe(c -> mCursorAdapter.changeCursor(c)); 52 | ``` 53 | 54 | You must call Disposable.dispose() when finished so that the library unregisters the ContentObserver 55 | 56 | ```java 57 | @Override 58 | protected void onStop() { 59 | super.onStop(); 60 | // stop using Cursor 61 | mAdapter.changeCursor(null); 62 | 63 | // Unsubscribe to close the Cursor and stop monitoring for ContentObserver changes 64 | mCursorDisposable.dispose(); 65 | } 66 | ``` 67 | 68 | If ContentResolver query returns null, `onError()` will be called with `QueryReturnedNullException` 69 | 70 | ## License 71 | 72 | ``` 73 | Copyright 2016 Yaroslav Mytkalyk 74 | 75 | Licensed under the Apache License, Version 2.0 (the "License"); 76 | you may not use this file except in compliance with the License. 77 | You may obtain a copy of the License at 78 | 79 | http://www.apache.org/licenses/LICENSE-2.0 80 | 81 | Unless required by applicable law or agreed to in writing, software 82 | distributed under the License is distributed on an "AS IS" BASIS, 83 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 84 | See the License for the specific language governing permissions and 85 | limitations under the License. 86 | 87 | ``` 88 | -------------------------------------------------------------------------------- /demo/src/main/java/com/doctoror/rxcursorloader/demo/DemoActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 Yaroslav Mytkalyk 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.doctoror.rxcursorloader.demo; 17 | 18 | import android.app.Activity; 19 | import android.database.Cursor; 20 | import android.os.Bundle; 21 | import android.widget.ListView; 22 | import android.widget.TextView; 23 | import android.widget.ViewAnimator; 24 | 25 | import com.doctoror.rxcursorloader.RxCursorLoader; 26 | 27 | import androidx.annotation.NonNull; 28 | import io.reactivex.BackpressureStrategy; 29 | import io.reactivex.android.schedulers.AndroidSchedulers; 30 | import io.reactivex.disposables.Disposable; 31 | import io.reactivex.schedulers.Schedulers; 32 | 33 | public final class DemoActivity extends Activity { 34 | 35 | private static final int ANIMATOR_CHILD_PROGRESS = 0; 36 | private static final int ANIMATOR_CHILD_ERROR = 1; 37 | private static final int ANIMATOR_CHILD_EMPTY = 2; 38 | private static final int ANIMATOR_CHILD_LIST = 3; 39 | 40 | private ViewAnimator mAnimator; 41 | private TextView mErrorText; 42 | private ListView mListView; 43 | 44 | private Disposable mCursorDisposable; 45 | private ArtistsCursorAdapter mAdapter; 46 | 47 | @Override 48 | protected void onCreate(Bundle savedInstanceState) { 49 | super.onCreate(savedInstanceState); 50 | setContentView(R.layout.activity_demo); 51 | mAnimator = findViewById(R.id.animator); 52 | mErrorText = findViewById(R.id.textError); 53 | mListView = findViewById(android.R.id.list); 54 | } 55 | 56 | @Override 57 | protected void onStart() { 58 | super.onStart(); 59 | mAnimator.setDisplayedChild(ANIMATOR_CHILD_PROGRESS); 60 | subscribe(); 61 | } 62 | 63 | @Override 64 | protected void onStop() { 65 | super.onStop(); 66 | if (mAdapter != null) { 67 | mAdapter.changeCursor(null); 68 | } 69 | if (mCursorDisposable != null) { 70 | mCursorDisposable.dispose(); 71 | mCursorDisposable = null; 72 | } 73 | } 74 | 75 | private void showError(@NonNull final CharSequence message) { 76 | mErrorText.setText(message); 77 | mAnimator.setDisplayedChild(ANIMATOR_CHILD_ERROR); 78 | } 79 | 80 | private void subscribe() { 81 | mCursorDisposable = RxCursorLoader.flowable(getContentResolver(), 82 | ArtistsQuery.QUERY, Schedulers.io(), BackpressureStrategy.LATEST) 83 | .observeOn(AndroidSchedulers.mainThread()) 84 | .subscribe(this::onCursorLoaded, this::onCursorLoadFailed); 85 | } 86 | 87 | private void onCursorLoaded(@NonNull final Cursor cursor) { 88 | if (mAdapter == null) { 89 | mAdapter = new ArtistsCursorAdapter(DemoActivity.this, cursor); 90 | mListView.setAdapter(mAdapter); 91 | } else { 92 | mAdapter.changeCursor(cursor); 93 | } 94 | mAnimator.setDisplayedChild(mAdapter.isEmpty() 95 | ? ANIMATOR_CHILD_EMPTY : ANIMATOR_CHILD_LIST); 96 | } 97 | 98 | private void onCursorLoadFailed(@NonNull final Throwable t) { 99 | showError(t.toString()); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /library/gradle-mvn-push.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Chris Banes 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | apply plugin: 'maven' 18 | apply plugin: 'signing' 19 | 20 | def isReleaseBuild() { 21 | return VERSION_NAME.contains("SNAPSHOT") == false 22 | } 23 | 24 | def getReleaseRepositoryUrl() { 25 | return hasProperty('RELEASE_REPOSITORY_URL') ? RELEASE_REPOSITORY_URL 26 | : "https://oss.sonatype.org/service/local/staging/deploy/maven2/" 27 | } 28 | 29 | def getSnapshotRepositoryUrl() { 30 | return hasProperty('SNAPSHOT_REPOSITORY_URL') ? SNAPSHOT_REPOSITORY_URL 31 | : "https://oss.sonatype.org/content/repositories/snapshots/" 32 | } 33 | 34 | def getRepositoryUsername() { 35 | return hasProperty('NEXUS_USERNAME') ? NEXUS_USERNAME : "" 36 | } 37 | 38 | def getRepositoryPassword() { 39 | return hasProperty('NEXUS_PASSWORD') ? NEXUS_PASSWORD : "" 40 | } 41 | 42 | afterEvaluate { project -> 43 | uploadArchives { 44 | repositories { 45 | mavenDeployer { 46 | beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } 47 | 48 | pom.groupId = GROUP 49 | pom.artifactId = POM_ARTIFACT_ID 50 | pom.version = VERSION_NAME 51 | 52 | repository(url: getReleaseRepositoryUrl()) { 53 | authentication(userName: getRepositoryUsername(), password: getRepositoryPassword()) 54 | } 55 | snapshotRepository(url: getSnapshotRepositoryUrl()) { 56 | authentication(userName: getRepositoryUsername(), password: getRepositoryPassword()) 57 | } 58 | 59 | pom.project { 60 | name POM_NAME 61 | packaging POM_PACKAGING 62 | description POM_DESCRIPTION 63 | url POM_URL 64 | 65 | scm { 66 | url POM_SCM_URL 67 | connection POM_SCM_CONNECTION 68 | developerConnection POM_SCM_DEV_CONNECTION 69 | } 70 | 71 | licenses { 72 | license { 73 | name POM_LICENCE_NAME 74 | url POM_LICENCE_URL 75 | distribution POM_LICENCE_DIST 76 | } 77 | } 78 | 79 | developers { 80 | developer { 81 | id POM_DEVELOPER_ID 82 | name POM_DEVELOPER_NAME 83 | } 84 | } 85 | } 86 | } 87 | } 88 | } 89 | 90 | signing { 91 | required { isReleaseBuild() && gradle.taskGraph.hasTask("uploadArchives") } 92 | sign configurations.archives 93 | } 94 | 95 | task androidJavadocs(type: Javadoc) { 96 | source = android.sourceSets.main.java.srcDirs 97 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) 98 | classpath += configurations.javadocDeps 99 | } 100 | 101 | task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) { 102 | classifier = 'javadoc' 103 | from androidJavadocs.destinationDir 104 | } 105 | 106 | task androidSourcesJar(type: Jar) { 107 | classifier = 'sources' 108 | from android.sourceSets.main.java.sourceFiles 109 | } 110 | 111 | artifacts { 112 | archives androidSourcesJar 113 | archives androidJavadocsJar 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /library/src/main/java/com/doctoror/rxcursorloader/RxCursorLoaderFlowableFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2018 Yaroslav Mytkalyk 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.doctoror.rxcursorloader; 17 | 18 | import android.content.ContentResolver; 19 | import android.database.ContentObserver; 20 | import android.database.Cursor; 21 | import android.os.Handler; 22 | import android.os.Looper; 23 | import android.util.Log; 24 | 25 | import androidx.annotation.NonNull; 26 | import io.reactivex.BackpressureStrategy; 27 | import io.reactivex.Flowable; 28 | import io.reactivex.FlowableEmitter; 29 | import io.reactivex.FlowableOnSubscribe; 30 | import io.reactivex.Scheduler; 31 | import io.reactivex.functions.Action; 32 | 33 | import static com.doctoror.rxcursorloader.RxCursorLoader.TAG; 34 | import static com.doctoror.rxcursorloader.RxCursorLoader.isDebugLoggingEnabled; 35 | 36 | final class RxCursorLoaderFlowableFactory { 37 | 38 | @NonNull 39 | static Flowable create( 40 | @NonNull final ContentResolver resolver, 41 | @NonNull final RxCursorLoader.Query query, 42 | @NonNull final Scheduler scheduler, 43 | @NonNull final BackpressureStrategy backpressureStrategy) { 44 | //noinspection ConstantConditions 45 | if (resolver == null) { 46 | throw new NullPointerException("ContentResolver must not be null"); 47 | } 48 | //noinspection ConstantConditions 49 | if (query == null) { 50 | throw new NullPointerException("Query must not be null"); 51 | } 52 | 53 | final CursorLoaderOnSubscribe onSubscribe = new CursorLoaderOnSubscribe( 54 | resolver, query, scheduler); 55 | 56 | return Flowable 57 | .create(onSubscribe, backpressureStrategy) 58 | .subscribeOn(scheduler) 59 | .doFinally(new Action() { 60 | @Override 61 | public void run() { 62 | onSubscribe.release(); 63 | } 64 | }); 65 | } 66 | 67 | private static final class CursorLoaderOnSubscribe 68 | implements FlowableOnSubscribe { 69 | 70 | private final Object mEmitterLock = new Object(); 71 | 72 | @NonNull 73 | private final ContentResolver mContentResolver; 74 | 75 | @NonNull 76 | private final RxCursorLoader.Query mQuery; 77 | 78 | @NonNull 79 | final Scheduler mScheduler; 80 | 81 | @NonNull 82 | private final Handler mHandler = new Handler(Looper.getMainLooper()); 83 | 84 | private FlowableEmitter mEmitter; 85 | 86 | CursorLoaderOnSubscribe( 87 | @NonNull final ContentResolver resolver, 88 | @NonNull final RxCursorLoader.Query query, 89 | @NonNull final Scheduler scheduler) { 90 | mContentResolver = resolver; 91 | mQuery = query; 92 | mScheduler = scheduler; 93 | } 94 | 95 | @Override 96 | public void subscribe(final FlowableEmitter emitter) { 97 | synchronized (mEmitterLock) { 98 | mEmitter = emitter; 99 | } 100 | mContentResolver.registerContentObserver( 101 | mQuery.contentUri, true, mContentObserver); 102 | reload(); 103 | } 104 | 105 | void release() { 106 | mContentResolver.unregisterContentObserver(mContentObserver); 107 | synchronized (mEmitterLock) { 108 | mEmitter = null; 109 | } 110 | } 111 | 112 | /** 113 | * Loads new {@link Cursor}. 114 | *

115 | * This must be called from {@link #subscribe(FlowableEmitter)} thread 116 | */ 117 | synchronized void reload() { 118 | if (isDebugLoggingEnabled()) { 119 | Log.d(TAG, mQuery.toString()); 120 | } 121 | 122 | final Cursor c = mContentResolver.query( 123 | mQuery.contentUri, 124 | mQuery.projection, 125 | mQuery.selection, 126 | mQuery.selectionArgs, 127 | mQuery.sortOrder); 128 | 129 | synchronized (mEmitterLock) { 130 | if (mEmitter != null && !mEmitter.isCancelled()) { 131 | if (c != null) { 132 | mEmitter.onNext(c); 133 | } else { 134 | mEmitter.onError(new QueryReturnedNullException()); 135 | } 136 | } 137 | } 138 | } 139 | 140 | private final ContentObserver mContentObserver = new ContentObserver(mHandler) { 141 | 142 | @Override 143 | public void onChange(final boolean selfChange) { 144 | mScheduler.scheduleDirect(mReloadRunnable); 145 | } 146 | }; 147 | 148 | final Runnable mReloadRunnable = new Runnable() { 149 | @Override 150 | public void run() { 151 | reload(); 152 | } 153 | }; 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /library/src/test/java/com/doctoror/rxcursorloader/RxCursorLoaderTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 Yaroslav Mytkalyk 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.doctoror.rxcursorloader; 17 | 18 | import android.content.ContentResolver; 19 | import android.database.Cursor; 20 | import android.net.Uri; 21 | import android.os.Parcel; 22 | import android.provider.MediaStore; 23 | 24 | import org.junit.Before; 25 | import org.junit.Test; 26 | import org.junit.runner.RunWith; 27 | import org.robolectric.RobolectricTestRunner; 28 | import org.robolectric.annotation.Config; 29 | 30 | import androidx.annotation.NonNull; 31 | import androidx.annotation.Nullable; 32 | import io.reactivex.BackpressureStrategy; 33 | import io.reactivex.observers.BaseTestConsumer; 34 | import io.reactivex.observers.TestObserver; 35 | import io.reactivex.schedulers.Schedulers; 36 | import io.reactivex.subscribers.TestSubscriber; 37 | 38 | import static org.junit.Assert.assertEquals; 39 | import static org.junit.Assert.assertNotNull; 40 | import static org.mockito.ArgumentMatchers.any; 41 | import static org.mockito.ArgumentMatchers.eq; 42 | import static org.mockito.Mockito.mock; 43 | import static org.mockito.Mockito.never; 44 | import static org.mockito.Mockito.verify; 45 | import static org.mockito.Mockito.when; 46 | 47 | @Config(manifest = Config.NONE) 48 | @RunWith(RobolectricTestRunner.class) 49 | public final class RxCursorLoaderTest { 50 | 51 | private static final Uri URI = new Uri.Builder().scheme("content") 52 | .authority("com.doctoror.rxcursorloader.test.provider").build(); 53 | 54 | private final ContentResolver contentResolver = mock(ContentResolver.class); 55 | 56 | @Before 57 | public void setup() { 58 | final Cursor stubCursor = mock(Cursor.class); 59 | when(contentResolver 60 | .query(eq(URI), (String[]) any(), (String) any(), (String[]) any(), (String) any())) 61 | .thenReturn(stubCursor); 62 | } 63 | 64 | private void assertHasValidOpenCursor(@NonNull final BaseTestConsumer observer) { 65 | observer.assertValueCount(1); 66 | assertValidOpenCursor((Cursor) observer.values().get(0)); 67 | } 68 | 69 | private void assertValidOpenCursor(@Nullable final Cursor c) { 70 | assertNotNull(c); 71 | verify(c, never()).close(); 72 | } 73 | 74 | private void givenQueryReturnsNull() { 75 | when(contentResolver 76 | .query(eq(URI), (String[]) any(), (String) any(), (String[]) any(), (String) any())) 77 | .thenReturn(null); 78 | } 79 | 80 | @NonNull 81 | private RxCursorLoader.Query buildQuery() { 82 | return new RxCursorLoader.Query.Builder() 83 | .setContentUri(URI).create(); 84 | } 85 | 86 | @Test(expected = IllegalStateException.class) 87 | public void noUriThrowsIllegalStateException() { 88 | //noinspection ConstantConditions 89 | RxCursorLoader.flowable( 90 | contentResolver, 91 | new RxCursorLoader.Query.Builder().create(), 92 | Schedulers.trampoline(), 93 | BackpressureStrategy.ERROR); 94 | } 95 | 96 | @Test(expected = NullPointerException.class) 97 | public void nullContentResolverThrowsNullPointerException() { 98 | //noinspection ConstantConditions 99 | RxCursorLoader.flowable( 100 | null, buildQuery(), Schedulers.trampoline(), BackpressureStrategy.ERROR); 101 | } 102 | 103 | @Test(expected = NullPointerException.class) 104 | public void nullQueryThrowsNullPointerException() { 105 | //noinspection ConstantConditions 106 | RxCursorLoader.flowable( 107 | contentResolver, null, Schedulers.trampoline(), BackpressureStrategy.ERROR); 108 | } 109 | 110 | @Test 111 | public void queryIsValidParcelable() { 112 | final RxCursorLoader.Query query = new RxCursorLoader.Query.Builder() 113 | .setContentUri(URI) 114 | .setProjection(new String[]{MediaStore.Audio.Media._ID}) 115 | .setSortOrder(MediaStore.Audio.Artists.ARTIST) 116 | .setSelection(MediaStore.Audio.Artists.ARTIST + "=?") 117 | .setSelectionArgs(new String[]{"Oh Long Johnson"}) 118 | .create(); 119 | 120 | final Parcel parcel = Parcel.obtain(); 121 | query.writeToParcel(parcel, 0); 122 | 123 | parcel.setDataPosition(0); 124 | 125 | final RxCursorLoader.Query fromParcel = RxCursorLoader.Query.CREATOR 126 | .createFromParcel(parcel); 127 | assertEquals(query, fromParcel); 128 | } 129 | 130 | @Test 131 | public void flowableReturnsCursorFromContentProvider() { 132 | final RxCursorLoader.Query query = new RxCursorLoader.Query.Builder() 133 | .setContentUri(URI) 134 | .create(); 135 | 136 | final TestSubscriber observer = RxCursorLoader.flowable( 137 | contentResolver, 138 | query, 139 | Schedulers.trampoline(), 140 | BackpressureStrategy.ERROR).test(); 141 | 142 | observer.assertNoErrors(); 143 | observer.assertNotComplete(); 144 | assertHasValidOpenCursor(observer); 145 | 146 | observer.dispose(); 147 | } 148 | 149 | @Test 150 | public void flowableErrorWhenProviderReturnsNull() { 151 | givenQueryReturnsNull(); 152 | 153 | final RxCursorLoader.Query query = new RxCursorLoader.Query.Builder() 154 | .setContentUri(URI) 155 | .create(); 156 | 157 | final TestSubscriber observer = RxCursorLoader.flowable( 158 | contentResolver, 159 | query, 160 | Schedulers.trampoline(), 161 | BackpressureStrategy.ERROR).test(); 162 | 163 | observer.assertError(QueryReturnedNullException.class); 164 | 165 | observer.dispose(); 166 | } 167 | 168 | @Test 169 | public void singleReturnsCursorFromContentProvider() { 170 | final RxCursorLoader.Query query = new RxCursorLoader.Query.Builder() 171 | .setContentUri(URI) 172 | .create(); 173 | 174 | final TestObserver observer = RxCursorLoader.single(contentResolver, query).test(); 175 | observer.assertNoErrors(); 176 | observer.assertComplete(); 177 | assertHasValidOpenCursor(observer); 178 | 179 | observer.dispose(); 180 | } 181 | 182 | @Test 183 | public void singleErrorWhenProviderReturnsNull() { 184 | givenQueryReturnsNull(); 185 | 186 | final RxCursorLoader.Query query = new RxCursorLoader.Query.Builder() 187 | .setContentUri(URI) 188 | .create(); 189 | 190 | final TestObserver observer = RxCursorLoader.single(contentResolver, query).test(); 191 | observer.assertError(QueryReturnedNullException.class); 192 | 193 | observer.dispose(); 194 | } 195 | } 196 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2016 Yaroslav Mytkalyk 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /library/src/main/java/com/doctoror/rxcursorloader/RxCursorLoader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 Yaroslav Mytkalyk 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.doctoror.rxcursorloader; 17 | 18 | import android.content.ContentResolver; 19 | import android.database.Cursor; 20 | import android.net.Uri; 21 | import android.os.Parcel; 22 | import android.os.Parcelable; 23 | 24 | import java.util.Arrays; 25 | 26 | import androidx.annotation.NonNull; 27 | import androidx.annotation.Nullable; 28 | import io.reactivex.BackpressureStrategy; 29 | import io.reactivex.Flowable; 30 | import io.reactivex.Observable; 31 | import io.reactivex.Observer; 32 | import io.reactivex.Scheduler; 33 | import io.reactivex.Single; 34 | import io.reactivex.disposables.Disposable; 35 | import io.reactivex.functions.Consumer; 36 | import io.reactivex.schedulers.Schedulers; 37 | 38 | /** 39 | * An RX replacement for {@link android.content.CursorLoader} 40 | *
41 | *
42 | * Usage: 43 | *
44 | * Create a {@link Query} using {@link Query.Builder}. The required parameter is only a content 45 | * URI. 46 | *

 47 |  * final RxCursorLoader.Query query = new RxCursorLoader.Query.Builder()
 48 |  *     .setContentUri(MediaStore.Audio.Media.INTERNAL_CONTENT_URI)
 49 |  *     .setProjection(new String[]{MediaStore.Audio.Media._ID})
 50 |  *     .setSortOrder(MediaStore.Audio.Artists.ARTIST)
 51 |  *     .setSelection(MediaStore.Audio.Artists.ARTIST + "=?")
 52 |  *     .setSelectionArgs(new String[] {"Oh Long Johnson"})
 53 |  *     .create();
 54 |  * }
 55 |  * 
56 | *

57 | * If you need to load only once, use {@link #single(ContentResolver, Query)}. 58 | *

59 | * If you need the loader to register ContentObserver and reload cursor passing it to onNext() 60 | * every time content changes, like {@link android.content.CursorLoader}, use 61 | * {@link #flowable(ContentResolver, Query, Scheduler, BackpressureStrategy)}. 62 | */ 63 | public final class RxCursorLoader { 64 | 65 | static final String TAG = "RxCursorLoader"; 66 | 67 | /** 68 | * Set this to true to enable debug logging 69 | */ 70 | private static boolean LOG_DEBUG = false; 71 | 72 | /** 73 | * Used to enable/disable debug level logs. 74 | *

75 | * Disabled by default. 76 | */ 77 | public static void setDebugLoggingEnabled(final boolean loggingEnabled) { 78 | LOG_DEBUG = loggingEnabled; 79 | } 80 | 81 | static boolean isDebugLoggingEnabled() { 82 | return LOG_DEBUG; 83 | } 84 | 85 | private RxCursorLoader() { 86 | throw new UnsupportedOperationException(); 87 | } 88 | 89 | /** 90 | * @deprecated use {@link #observable(ContentResolver, Query, Scheduler)} instead. 91 | */ 92 | @Deprecated 93 | @NonNull 94 | public static Observable create( 95 | @NonNull final ContentResolver resolver, 96 | @NonNull final Query query) { 97 | return observable(resolver, query, Schedulers.io()); 98 | } 99 | 100 | /** 101 | * Create a new {@link Observable} that emits items from a {@link ContentResolver} query. 102 | * This acts like {@link android.content.CursorLoader}. 103 | *

104 | * When a non-null Cursor is loaded, it is passed to {@link Observer#onNext(Object)}}. 105 | *

106 | * If the query returns null, {@link QueryReturnedNullException} is passed to 107 | * {@link Observer#onError(Throwable)}. 108 | *

109 | * Every time the content changes, the Cursor will be reloaded and passed to {@link 110 | * Observer#onNext(Object)}. 111 | *

112 | * Make sure to close old cursor because cursors are not automatically closed 113 | *

114 | * {@link Observer#onError(Throwable)}} is called if {@link RuntimeException} is caught when running a 115 | * query. 116 | *

117 | * You must call {@link Disposable#dispose()} when finished. 118 | *

119 | *

120 |      * protected void onStop() {
121 |      *     super.onStop();
122 |      *     // stop using Cursor and close it
123 |      *     mAdapter.changeCursor(null);
124 |      *     // Unsubscribe to stop monitoring for ContentObserver changes
125 |      *     mCursorDisposable.dispose();
126 |      * }
127 |      * 
128 | * 129 | * @param resolver {@link ContentResolver} to use 130 | * @param query the {@link Query} to use 131 | * @param scheduler the {@link Scheduler} to emit items from. This will automatically set 132 | * {@link Observable#subscribeOn(Scheduler)} with this scheduler. Even if you change the 133 | * scheduler afterwards, the subsequent items will be still emitted from this scheduler. 134 | * @return new {@link Observable}. 135 | */ 136 | @NonNull 137 | public static Observable observable( 138 | @NonNull final ContentResolver resolver, 139 | @NonNull final Query query, 140 | @NonNull final Scheduler scheduler) { 141 | return RxCursorLoaderFlowableFactory 142 | .create(resolver, query, scheduler, BackpressureStrategy.MISSING) 143 | .toObservable(); 144 | } 145 | 146 | /** 147 | * Create a new {@link Flowable} that emits items from a {@link ContentResolver} query. 148 | * This acts like {@link android.content.CursorLoader}. 149 | *

150 | * When a non-null Cursor is loaded, it is passed to {@link Observer#onNext(Object)}}. 151 | *

152 | * If the query returns null, {@link QueryReturnedNullException} is passed to 153 | * {@link Observer#onError(Throwable)}. 154 | *

155 | * Every time the content changes, the Cursor will be reloaded and passed to {@link 156 | * Observer#onNext(Object)}. 157 | *

158 | * Make sure to close old cursor because cursors are not automatically closed 159 | *

160 | * {@link Observer#onError(Throwable)}} is called if {@link RuntimeException} is caught when running a 161 | * query. 162 | *

163 | * You must call {@link Disposable#dispose()} when finished. 164 | *

165 | *

166 |      * protected void onStop() {
167 |      *     super.onStop();
168 |      *     // stop using Cursor and close it
169 |      *     mAdapter.changeCursor(null);
170 |      *     // Unsubscribe to stop monitoring for ContentObserver changes
171 |      *     mCursorDisposable.dispose();
172 |      * }
173 |      * 
174 | * 175 | * @param resolver {@link ContentResolver} to use 176 | * @param query the {@link Query} to use 177 | * @param scheduler the {@link Scheduler} to emit items from. This will automatically set 178 | * {@link Flowable#subscribeOn(Scheduler)} with this scheduler. Even if you 179 | * change the 180 | * scheduler afterwards, the subsequent items will be still emitted from this 181 | * scheduler. 182 | * @param backpressureStrategy the {@link BackpressureStrategy} to use. 183 | * @return new {@link Flowable}. 184 | */ 185 | @NonNull 186 | public static Flowable flowable( 187 | @NonNull final ContentResolver resolver, 188 | @NonNull final Query query, 189 | @NonNull final Scheduler scheduler, 190 | @NonNull final BackpressureStrategy backpressureStrategy) { 191 | return RxCursorLoaderFlowableFactory 192 | .create(resolver, query, scheduler, backpressureStrategy); 193 | } 194 | 195 | /** 196 | * Create a new {@link Single} that loads {@link Cursor} once and does not close it. 197 | * Calls {@link Consumer#accept(Object)} once non-null {@link Cursor} is loaded. 198 | * If the query returns null, {@link QueryReturnedNullException} is thrown. 199 | * 200 | * @param resolver {@link ContentResolver} to use 201 | * @param query the {@link Query} to use 202 | * @return new {@link Single}. 203 | */ 204 | @NonNull 205 | public static Single single( 206 | @NonNull final ContentResolver resolver, 207 | @NonNull final Query query) { 208 | return RxCursorLoaderSingleFactory.single(resolver, query); 209 | } 210 | 211 | /** 212 | * Parameters for {@link RxCursorLoader} 213 | */ 214 | public static final class Query implements Parcelable { 215 | 216 | Uri contentUri; 217 | String[] projection; 218 | String selection; 219 | String[] selectionArgs; 220 | String sortOrder; 221 | 222 | Query() { 223 | 224 | } 225 | 226 | Query(@NonNull final Parcel p) { 227 | contentUri = p.readParcelable(Uri.class.getClassLoader()); 228 | projection = p.createStringArray(); 229 | selection = p.readString(); 230 | selectionArgs = p.createStringArray(); 231 | sortOrder = p.readString(); 232 | } 233 | 234 | @Override 235 | public void writeToParcel(@NonNull final Parcel p, final int i) { 236 | p.writeParcelable(contentUri, 0); 237 | p.writeStringArray(projection); 238 | p.writeString(selection); 239 | p.writeStringArray(selectionArgs); 240 | p.writeString(sortOrder); 241 | } 242 | 243 | @Override 244 | public int describeContents() { 245 | return 0; 246 | } 247 | 248 | // Generated by Android Studio 249 | @Override 250 | public boolean equals(final Object o) { 251 | if (this == o) { 252 | return true; 253 | } 254 | if (o == null || getClass() != o.getClass()) { 255 | return false; 256 | } 257 | 258 | final Query query = (Query) o; 259 | 260 | if (contentUri != null ? !contentUri.equals(query.contentUri) 261 | : query.contentUri != null) { 262 | return false; 263 | } 264 | // Probably incorrect - comparing Object[] arrays with Arrays.equals 265 | if (!Arrays.equals(projection, query.projection)) { 266 | return false; 267 | } 268 | if (selection != null ? !selection.equals(query.selection) : query.selection != null) { 269 | return false; 270 | } 271 | // Probably incorrect - comparing Object[] arrays with Arrays.equals 272 | //noinspection SimplifiableIfStatement 273 | if (!Arrays.equals(selectionArgs, query.selectionArgs)) { 274 | return false; 275 | } 276 | return sortOrder != null ? sortOrder.equals(query.sortOrder) : query.sortOrder == null; 277 | 278 | } 279 | 280 | // Generated by Android Studio 281 | @Override 282 | public int hashCode() { 283 | int result = contentUri != null ? contentUri.hashCode() : 0; 284 | result = 31 * result + Arrays.hashCode(projection); 285 | result = 31 * result + (selection != null ? selection.hashCode() : 0); 286 | result = 31 * result + Arrays.hashCode(selectionArgs); 287 | result = 31 * result + (sortOrder != null ? sortOrder.hashCode() : 0); 288 | return result; 289 | } 290 | 291 | @Override 292 | public String toString() { 293 | return "Params{" + 294 | "mContentUri=" + contentUri + 295 | ", mProjection=" + Arrays.toString(projection) + 296 | ", mSelection='" + selection + '\'' + 297 | ", mSelectionArgs=" + Arrays.toString(selectionArgs) + 298 | ", mSortOrder='" + sortOrder + '\'' + 299 | '}'; 300 | } 301 | 302 | public static final Parcelable.Creator CREATOR = new Creator() { 303 | 304 | @Override 305 | public Query createFromParcel(final Parcel parcel) { 306 | return new Query(parcel); 307 | } 308 | 309 | @Override 310 | public Query[] newArray(final int size) { 311 | return new Query[size]; 312 | } 313 | }; 314 | 315 | /** 316 | * {@link Query} builder. 317 | *

318 | * The only required parameter is a content URI. 319 | */ 320 | public static final class Builder { 321 | 322 | private Uri mContentUri; 323 | private String[] mProjection; 324 | private String mSelection; 325 | private String[] mSelectionArgs; 326 | private String mSortOrder; 327 | 328 | public Builder() { 329 | 330 | } 331 | 332 | @NonNull 333 | public Builder setContentUri(@NonNull final Uri contentUri) { 334 | mContentUri = contentUri; 335 | return this; 336 | } 337 | 338 | @NonNull 339 | public Builder setProjection(@Nullable final String[] projection) { 340 | mProjection = projection; 341 | return this; 342 | } 343 | 344 | @NonNull 345 | public Builder setSelection(@Nullable final String selection) { 346 | mSelection = selection; 347 | return this; 348 | } 349 | 350 | @NonNull 351 | public Builder setSelectionArgs(@Nullable final String[] selectionArgs) { 352 | mSelectionArgs = selectionArgs; 353 | return this; 354 | } 355 | 356 | @NonNull 357 | public Builder setSortOrder(@Nullable final String sortOrder) { 358 | mSortOrder = sortOrder; 359 | return this; 360 | } 361 | 362 | /** 363 | * Creates the {@link Query} 364 | * 365 | * @return the {@link Query} 366 | * @throws IllegalStateException if content uri is null 367 | */ 368 | @NonNull 369 | public Query create() { 370 | if (mContentUri == null) { 371 | throw new IllegalStateException("Content URI not set"); 372 | } 373 | final Query query = new Query(); 374 | query.contentUri = mContentUri; 375 | query.projection = mProjection; 376 | query.selection = mSelection; 377 | query.selectionArgs = mSelectionArgs; 378 | query.sortOrder = mSortOrder; 379 | return query; 380 | } 381 | } 382 | } 383 | } 384 | --------------------------------------------------------------------------------