├── .github └── workflows │ └── build_test.yml ├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── example │ │ └── android │ │ └── roomwordssample │ │ ├── LiveDataTestUtil.java │ │ └── WordDaoTest.java │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── example │ │ └── android │ │ └── roomwordssample │ │ ├── MainActivity.java │ │ ├── NewWordActivity.java │ │ ├── Word.java │ │ ├── WordDao.java │ │ ├── WordListAdapter.java │ │ ├── WordRepository.java │ │ ├── WordRoomDatabase.java │ │ ├── WordViewHolder.java │ │ └── WordViewModel.java │ └── res │ ├── drawable │ ├── ic_add_black_24dp.xml │ └── ic_launcher_background.xml │ ├── layout │ ├── activity_main.xml │ ├── activity_new_word.xml │ ├── content_main.xml │ └── recyclerview_item.xml │ ├── mipmap-anydpi-v26 │ ├── ic_launcher.xml │ └── ic_launcher_round.xml │ ├── mipmap-hdpi │ ├── ic_launcher.png │ ├── ic_launcher_foreground.png │ └── ic_launcher_round.png │ ├── mipmap-mdpi │ ├── ic_launcher.png │ ├── ic_launcher_foreground.png │ └── ic_launcher_round.png │ ├── mipmap-xhdpi │ ├── ic_launcher.png │ ├── ic_launcher_foreground.png │ └── ic_launcher_round.png │ ├── mipmap-xxhdpi │ ├── ic_launcher.png │ ├── ic_launcher_foreground.png │ └── ic_launcher_round.png │ ├── mipmap-xxxhdpi │ ├── ic_launcher.png │ ├── ic_launcher_foreground.png │ └── ic_launcher_round.png │ └── values │ ├── colors.xml │ ├── dimens.xml │ ├── strings.xml │ └── styles.xml ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.github/workflows/build_test.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | # Controls when the action will run. Triggers the workflow on push or pull request 4 | # events for the `master` and `kotlin` branches 5 | on: 6 | push: 7 | branches: 8 | - master 9 | - kotlin 10 | pull_request: 11 | branches: 12 | - master 13 | - kotlin 14 | 15 | # A workflow run is made up of one or more jobs that can run sequentially or in parallel 16 | jobs: 17 | 18 | # Build will compile APK, test APK and run tests, lint, etc. 19 | build: 20 | # The type of runner that the job will run on 21 | runs-on: ubuntu-latest 22 | timeout-minutes: 45 23 | env: 24 | TERM: dumb 25 | 26 | # Steps represent a sequence of tasks that will be executed as part of the job 27 | steps: 28 | # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it 29 | - uses: actions/checkout@v2 30 | 31 | - name: set up JDK 1.8 32 | uses: actions/setup-java@v1 33 | with: 34 | java-version: 1.8 35 | - name: Build and check 36 | run: ./gradlew assembleDebug assembleDebugAndroidTest app:lintDebug testDebug 37 | 38 | - name: Upload build reports 39 | if: always() 40 | uses: actions/upload-artifact@v1 41 | with: 42 | name: build-reports 43 | path: app/build/reports 44 | 45 | - name: Copy test results 46 | if: always() 47 | run: | 48 | mkdir -p junit 49 | find . -type f -regex ".*/build/test-results/.*xml" -exec cp {} junit/ \; 50 | 51 | - name: Upload test results 52 | if: always() 53 | uses: actions/upload-artifact@v1 54 | with: 55 | name: junit-results 56 | path: junit 57 | 58 | - name: Upload app APK 59 | uses: actions/upload-artifact@v1 60 | with: 61 | name: app-debug 62 | path: app/build/outputs/apk/debug/app-debug.apk 63 | 64 | - name: Upload Android Test APK 65 | uses: actions/upload-artifact@v1 66 | with: 67 | name: app-debug-androidTest 68 | path: app/build/outputs/apk/androidTest/debug/app-debug-androidTest.apk 69 | 70 | 71 | # Upload APKs to FTL and run instrumented tests 72 | firebase: 73 | name: Run UI tests with Firebase Test Lab 74 | needs: build 75 | runs-on: ubuntu-18.04 76 | 77 | steps: 78 | - uses: actions/checkout@v1 79 | 80 | - name: Download app APK 81 | uses: actions/download-artifact@v1 82 | with: 83 | name: app-debug 84 | 85 | - name: Download Android test APK 86 | uses: actions/download-artifact@v1 87 | with: 88 | name: app-debug-androidTest 89 | 90 | - name: Login to Google Cloud 91 | uses: GoogleCloudPlatform/github-actions/setup-gcloud@master 92 | with: 93 | version: '281.0.0' 94 | service_account_key: ${{ secrets.FTL_KEY_BASE64 }} 95 | 96 | - name: Set current project 97 | run: gcloud config set project ${{ secrets.FIREBASE_PROJECT_ID }} 98 | 99 | - name: Run Instrumentation Tests in Firebase Test Lab 100 | run: gcloud firebase test android run --type instrumentation --app app-debug/app-debug.apk --test app-debug-androidTest/app-debug-androidTest.apk --device model=Pixel2,version=28,locale=pl,orientation=portrait 101 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .idea 3 | .gradle 4 | /local.properties 5 | .DS_Store 6 | build/ 7 | /captures 8 | .externalNativeBuild 9 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to become a contributor and submit your own code 2 | 3 | ## Contributor License Agreements 4 | 5 | We'd love to accept your sample apps and patches! Before we can take them, we 6 | have to jump a couple of legal hurdles. 7 | 8 | Please fill out either the individual or corporate Contributor License Agreement 9 | (CLA). 10 | 11 | * If you are an individual writing original source code and you're sure you 12 | own the intellectual property, then you'll need to sign an [individual CLA] 13 | (https://developers.google.com/open-source/cla/individual). 14 | * If you work for a company that wants to allow you to contribute your work, 15 | then you'll need to sign a [corporate CLA] 16 | (https://developers.google.com/open-source/cla/corporate). 17 | 18 | Follow either of the two links above to access the appropriate CLA and 19 | instructions for how to sign and return it. Once we receive it, we'll be able to 20 | accept your pull requests. 21 | 22 | ## Contributing A Patch 23 | 24 | 1. Submit an issue describing your proposed change to the repo in question. 25 | 1. The repo owner will respond to your issue promptly. 26 | 1. If your proposed change is accepted, and you haven't already done so, sign a 27 | Contributor License Agreement (see details above). 28 | 1. Fork the desired repo, develop and test your code changes. 29 | 1. Ensure that your code adheres to the existing style in the sample to which 30 | you are contributing. Refer to the 31 | [Google Cloud Platform Samples Style Guide] 32 | (https://github.com/GoogleCloudPlatform/Template/wiki/style.html) for the 33 | recommended coding standards for this organization. 34 | 1. Ensure that your code has an appropriate set of unit tests which all pass. 35 | 1. Submit a pull request. 36 | 37 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | -------------- 3 | 4 | Version 2.0, January 2004 5 | http://www.apache.org/licenses/ 6 | 7 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 8 | 9 | 1. Definitions. 10 | 11 | "License" shall mean the terms and conditions for use, reproduction, 12 | and distribution as defined by Sections 1 through 9 of this document. 13 | 14 | "Licensor" shall mean the copyright owner or entity authorized by 15 | the copyright owner that is granting the License. 16 | 17 | "Legal Entity" shall mean the union of the acting entity and all 18 | other entities that control, are controlled by, or are under common 19 | control with that entity. For the purposes of this definition, 20 | "control" means (i) the power, direct or indirect, to cause the 21 | direction or management of such entity, whether by contract or 22 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 23 | outstanding shares, or (iii) beneficial ownership of such entity. 24 | 25 | "You" (or "Your") shall mean an individual or Legal Entity 26 | exercising permissions granted by this License. 27 | 28 | "Source" form shall mean the preferred form for making modifications, 29 | including but not limited to software source code, documentation 30 | source, and configuration files. 31 | 32 | "Object" form shall mean any form resulting from mechanical 33 | transformation or translation of a Source form, including but 34 | not limited to compiled object code, generated documentation, 35 | and conversions to other media types. 36 | 37 | "Work" shall mean the work of authorship, whether in Source or 38 | Object form, made available under the License, as indicated by a 39 | copyright notice that is included in or attached to the work 40 | (an example is provided in the Appendix below). 41 | 42 | "Derivative Works" shall mean any work, whether in Source or Object 43 | form, that is based on (or derived from) the Work and for which the 44 | editorial revisions, annotations, elaborations, or other modifications 45 | represent, as a whole, an original work of authorship. For the purposes 46 | of this License, Derivative Works shall not include works that remain 47 | separable from, or merely link (or bind by name) to the interfaces of, 48 | the Work and Derivative Works thereof. 49 | 50 | "Contribution" shall mean any work of authorship, including 51 | the original version of the Work and any modifications or additions 52 | to that Work or Derivative Works thereof, that is intentionally 53 | submitted to Licensor for inclusion in the Work by the copyright owner 54 | or by an individual or Legal Entity authorized to submit on behalf of 55 | the copyright owner. For the purposes of this definition, "submitted" 56 | means any form of electronic, verbal, or written communication sent 57 | to the Licensor or its representatives, including but not limited to 58 | communication on electronic mailing lists, source code control systems, 59 | and issue tracking systems that are managed by, or on behalf of, the 60 | Licensor for the purpose of discussing and improving the Work, but 61 | excluding communication that is conspicuously marked or otherwise 62 | designated in writing by the copyright owner as "Not a Contribution." 63 | 64 | "Contributor" shall mean Licensor and any individual or Legal Entity 65 | on behalf of whom a Contribution has been received by Licensor and 66 | subsequently incorporated within the Work. 67 | 68 | 2. Grant of Copyright License. Subject to the terms and conditions of 69 | this License, each Contributor hereby grants to You a perpetual, 70 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 71 | copyright license to reproduce, prepare Derivative Works of, 72 | publicly display, publicly perform, sublicense, and distribute the 73 | Work and such Derivative Works in Source or Object form. 74 | 75 | 3. Grant of Patent License. Subject to the terms and conditions of 76 | this License, each Contributor hereby grants to You a perpetual, 77 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 78 | (except as stated in this section) patent license to make, have made, 79 | use, offer to sell, sell, import, and otherwise transfer the Work, 80 | where such license applies only to those patent claims licensable 81 | by such Contributor that are necessarily infringed by their 82 | Contribution(s) alone or by combination of their Contribution(s) 83 | with the Work to which such Contribution(s) was submitted. If You 84 | institute patent litigation against any entity (including a 85 | cross-claim or counterclaim in a lawsuit) alleging that the Work 86 | or a Contribution incorporated within the Work constitutes direct 87 | or contributory patent infringement, then any patent licenses 88 | granted to You under this License for that Work shall terminate 89 | as of the date such litigation is filed. 90 | 91 | 4. Redistribution. You may reproduce and distribute copies of the 92 | Work or Derivative Works thereof in any medium, with or without 93 | modifications, and in Source or Object form, provided that You 94 | meet the following conditions: 95 | 96 | (a) You must give any other recipients of the Work or 97 | Derivative Works a copy of this License; and 98 | 99 | (b) You must cause any modified files to carry prominent notices 100 | stating that You changed the files; and 101 | 102 | (c) You must retain, in the Source form of any Derivative Works 103 | that You distribute, all copyright, patent, trademark, and 104 | attribution notices from the Source form of the Work, 105 | excluding those notices that do not pertain to any part of 106 | the Derivative Works; and 107 | 108 | (d) If the Work includes a "NOTICE" text file as part of its 109 | distribution, then any Derivative Works that You distribute must 110 | include a readable copy of the attribution notices contained 111 | within such NOTICE file, excluding those notices that do not 112 | pertain to any part of the Derivative Works, in at least one 113 | of the following places: within a NOTICE text file distributed 114 | as part of the Derivative Works; within the Source form or 115 | documentation, if provided along with the Derivative Works; or, 116 | within a display generated by the Derivative Works, if and 117 | wherever such third-party notices normally appear. The contents 118 | of the NOTICE file are for informational purposes only and 119 | do not modify the License. You may add Your own attribution 120 | notices within Derivative Works that You distribute, alongside 121 | or as an addendum to the NOTICE text from the Work, provided 122 | that such additional attribution notices cannot be construed 123 | as modifying the License. 124 | 125 | You may add Your own copyright statement to Your modifications and 126 | may provide additional or different license terms and conditions 127 | for use, reproduction, or distribution of Your modifications, or 128 | for any such Derivative Works as a whole, provided Your use, 129 | reproduction, and distribution of the Work otherwise complies with 130 | the conditions stated in this License. 131 | 132 | 5. Submission of Contributions. Unless You explicitly state otherwise, 133 | any Contribution intentionally submitted for inclusion in the Work 134 | by You to the Licensor shall be under the terms and conditions of 135 | this License, without any additional terms or conditions. 136 | Notwithstanding the above, nothing herein shall supersede or modify 137 | the terms of any separate license agreement you may have executed 138 | with Licensor regarding such Contributions. 139 | 140 | 6. Trademarks. This License does not grant permission to use the trade 141 | names, trademarks, service marks, or product names of the Licensor, 142 | except as required for reasonable and customary use in describing the 143 | origin of the Work and reproducing the content of the NOTICE file. 144 | 145 | 7. Disclaimer of Warranty. Unless required by applicable law or 146 | agreed to in writing, Licensor provides the Work (and each 147 | Contributor provides its Contributions) on an "AS IS" BASIS, 148 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 149 | implied, including, without limitation, any warranties or conditions 150 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 151 | PARTICULAR PURPOSE. You are solely responsible for determining the 152 | appropriateness of using or redistributing the Work and assume any 153 | risks associated with Your exercise of permissions under this License. 154 | 155 | 8. Limitation of Liability. In no event and under no legal theory, 156 | whether in tort (including negligence), contract, or otherwise, 157 | unless required by applicable law (such as deliberate and grossly 158 | negligent acts) or agreed to in writing, shall any Contributor be 159 | liable to You for damages, including any direct, indirect, special, 160 | incidental, or consequential damages of any character arising as a 161 | result of this License or out of the use or inability to use the 162 | Work (including but not limited to damages for loss of goodwill, 163 | work stoppage, computer failure or malfunction, or any and all 164 | other commercial damages or losses), even if such Contributor 165 | has been advised of the possibility of such damages. 166 | 167 | 9. Accepting Warranty or Additional Liability. While redistributing 168 | the Work or Derivative Works thereof, You may choose to offer, 169 | and charge a fee for, acceptance of support, warranty, indemnity, 170 | or other liability obligations and/or rights consistent with this 171 | License. However, in accepting such obligations, You may act only 172 | on Your own behalf and on Your sole responsibility, not on behalf 173 | of any other Contributor, and only if You agree to indemnify, 174 | defend, and hold each Contributor harmless for any liability 175 | incurred by, or claims asserted against, such Contributor by reason 176 | of your accepting any such warranty or additional liability. 177 | 178 | END OF TERMS AND CONDITIONS 179 | 180 | APPENDIX: How to apply the Apache License to your work. 181 | 182 | To apply the Apache License to your work, attach the following 183 | boilerplate notice, with the fields enclosed by brackets "{}" 184 | replaced with your own identifying information. (Don't include 185 | the brackets!) The text should be enclosed in the appropriate 186 | comment syntax for the file format. We also recommend that a 187 | file or class name and description of purpose be included on the 188 | same "printed page" as the copyright notice for easier 189 | identification within third-party archives. 190 | 191 | Copyright {yyyy} {name of copyright owner} 192 | 193 | Licensed under the Apache License, Version 2.0 (the "License"); 194 | you may not use this file except in compliance with the License. 195 | You may obtain a copy of the License at 196 | 197 | http://www.apache.org/licenses/LICENSE-2.0 198 | 199 | Unless required by applicable law or agreed to in writing, software 200 | distributed under the License is distributed on an "AS IS" BASIS, 201 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 202 | See the License for the specific language governing permissions and 203 | limitations under the License. 204 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | > # This codelab is deprecated and it will be removed soon. 2 | 3 | RoomWordsSample 4 | ================ 5 | 6 | This repository contains the finished sample code for the 7 | [Architecture Components codelab](https://codelabs.developers.google.com/codelabs/android-room-with-a-view/index.html?index=..%2F..%2Findex#0) in Java on the master branch and in Kotlin for the [Architecture Components Kotlin codelab](https://codelabs.developers.google.com/codelabs/android-room-with-a-view-kotlin) on the [kotlin](https://github.com/googlecodelabs/android-room-with-a-view/tree/kotlin) branch. 8 | 9 | Introduction 10 | ------------ 11 | 12 | In May 2017 Google released the Architecture Components libraries. 13 | Each library manages and simplifies aspects of data persistence and the 14 | UI component lifecycle. Together, the libraries encourage a modular 15 | app architecture that results in reduced complexity and less code. 16 | 17 | This sample shows how to use the libraries to build 18 | a complete basic app that implements the recommended architecture 19 | and can be used as a template for further explorations. 20 | 21 | 22 | Pre-requisites 23 | -------------- 24 | 25 | * Android Studio 3.0 or later and you know how to use it. 26 | 27 | * Make sure Android Studio is updated, as well as your SDK and Gradle. 28 | Otherwise, you may have to wait for a while until all the updates are done. 29 | 30 | * A device or emulator that runs SDK level 20 31 | 32 | You need to be solidly familiar with the Java programming language, 33 | object-oriented design concepts, and Android Development Fundamentals. 34 | In particular: 35 | 36 | * RecyclerView and Adapters 37 | * SQLite database and the SQLite query language 38 | * Threading and ExecutorService 39 | * It helps to be familiar with software architectural patterns that separate 40 | data from the user interface, such as MVP or MVC. This codelab implements the 41 | architecture defined in the 42 | [Guide to App Architecture]( 43 | https://developer.android.com/topic/libraries/architecture/guide.html) 44 | 45 | Getting Started 46 | --------------- 47 | 48 | 1. [Install Android Studio](https://developer.android.com/studio/install.html), 49 | if you don't already have it. 50 | 2. Download the sample. 51 | 2. Import the sample into Android Studio. 52 | 3. Build and run the sample. 53 | 54 | License 55 | ------- 56 | 57 | Copyright 2019 Google, Inc. 58 | 59 | All image and audio files (including *.png, *.jpg, *.svg, *.mp3, *.wav 60 | and *.ogg) are licensed under the CC BY 4.0 license. All other files are 61 | licensed under the Apache 2 license. 62 | 63 | Licensed to the Apache Software Foundation (ASF) under one or more contributor 64 | license agreements. See the LICENSE file distributed with this work for 65 | additional information regarding copyright ownership. The ASF licenses this 66 | file to you under the Apache License, Version 2.0 (the "License"); you may not 67 | use this file except in compliance with the License. You may obtain a copy of 68 | the License at 69 | 70 | http://www.apache.org/licenses/LICENSE-2.0 71 | 72 | Unless required by applicable law or agreed to in writing, software 73 | distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 74 | WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 75 | License for the specific language governing permissions and limitations under 76 | the License. 77 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.android.application' 3 | } 4 | 5 | android { 6 | compileSdkVersion 30 7 | defaultConfig { 8 | applicationId "com.example.android.roomwordssample" 9 | minSdkVersion 20 10 | targetSdkVersion 30 11 | versionCode 1 12 | versionName "1.0" 13 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 14 | } 15 | buildTypes { 16 | release { 17 | minifyEnabled false 18 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 19 | } 20 | } 21 | compileOptions { 22 | sourceCompatibility = 1.8 23 | targetCompatibility = 1.8 24 | } 25 | } 26 | 27 | dependencies { 28 | implementation "androidx.appcompat:appcompat:$rootProject.appCompatVersion" 29 | 30 | // Dependencies for working with Architecture components 31 | // You'll probably have to update the version numbers in build.gradle (Project) 32 | 33 | // Room components 34 | implementation "androidx.room:room-runtime:$rootProject.roomVersion" 35 | annotationProcessor "androidx.room:room-compiler:$rootProject.roomVersion" 36 | androidTestImplementation "androidx.room:room-testing:$rootProject.roomVersion" 37 | 38 | // Lifecycle components 39 | implementation "androidx.lifecycle:lifecycle-viewmodel:$rootProject.lifecycleVersion" 40 | implementation "androidx.lifecycle:lifecycle-livedata:$rootProject.lifecycleVersion" 41 | implementation "androidx.lifecycle:lifecycle-common-java8:$rootProject.lifecycleVersion" 42 | 43 | // UI 44 | implementation "androidx.constraintlayout:constraintlayout:$rootProject.constraintLayoutVersion" 45 | implementation "com.google.android.material:material:$rootProject.materialVersion" 46 | 47 | // Testing 48 | testImplementation "junit:junit:$rootProject.junitVersion" 49 | androidTestImplementation "androidx.arch.core:core-testing:$rootProject.coreTestingVersion" 50 | androidTestImplementation ("androidx.test.espresso:espresso-core:$rootProject.espressoVersion", { 51 | exclude group: 'com.android.support', module: 'support-annotations' 52 | }) 53 | androidTestImplementation "androidx.test.ext:junit:$rootProject.androidxJunitVersion" 54 | } 55 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/example/android/roomwordssample/LiveDataTestUtil.java: -------------------------------------------------------------------------------- 1 | package com.example.android.roomwordssample; 2 | /* 3 | * Copyright (C) 2017 The Android Open Source Project 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | import androidx.lifecycle.LiveData; 19 | import androidx.lifecycle.Observer; 20 | import androidx.annotation.Nullable; 21 | 22 | import java.util.concurrent.CountDownLatch; 23 | import java.util.concurrent.TimeUnit; 24 | 25 | public class LiveDataTestUtil { 26 | 27 | /** 28 | * Get the value from a LiveData object. We're waiting for LiveData to emit, for 2 seconds. 29 | * Once we got a notification via onChanged, we stop observing. 30 | */ 31 | public static T getValue(final LiveData liveData) throws InterruptedException { 32 | final Object[] data = new Object[1]; 33 | final CountDownLatch latch = new CountDownLatch(1); 34 | Observer observer = new Observer() { 35 | @Override 36 | public void onChanged(@Nullable T o) { 37 | data[0] = o; 38 | latch.countDown(); 39 | liveData.removeObserver(this); 40 | } 41 | }; 42 | liveData.observeForever(observer); 43 | latch.await(2, TimeUnit.SECONDS); 44 | //noinspection unchecked 45 | return (T) data[0]; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/example/android/roomwordssample/WordDaoTest.java: -------------------------------------------------------------------------------- 1 | package com.example.android.roomwordssample; 2 | 3 | /* 4 | * Copyright (C) 2017 Google Inc. 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | import static junit.framework.Assert.assertEquals; 20 | import static junit.framework.Assert.assertTrue; 21 | 22 | import android.content.Context; 23 | 24 | import org.junit.After; 25 | import org.junit.Before; 26 | import org.junit.Rule; 27 | import org.junit.Test; 28 | import org.junit.runner.RunWith; 29 | 30 | import java.util.List; 31 | 32 | import androidx.arch.core.executor.testing.InstantTaskExecutorRule; 33 | import androidx.room.Room; 34 | import androidx.test.core.app.ApplicationProvider; 35 | import androidx.test.ext.junit.runners.AndroidJUnit4; 36 | 37 | /** 38 | * This is not meant to be a full set of tests. For simplicity, most of your samples do not 39 | * include tests. However, when building the Room, it is helpful to make sure it works before 40 | * adding the UI. 41 | */ 42 | 43 | @RunWith(AndroidJUnit4.class) 44 | public class WordDaoTest { 45 | 46 | @Rule 47 | public InstantTaskExecutorRule instantTaskExecutorRule = new InstantTaskExecutorRule(); 48 | 49 | private WordDao mWordDao; 50 | private WordRoomDatabase mDb; 51 | 52 | @Before 53 | public void createDb() { 54 | Context context = ApplicationProvider.getApplicationContext(); 55 | // Using an in-memory database because the information stored here disappears when the 56 | // process is killed. 57 | mDb = Room.inMemoryDatabaseBuilder(context, WordRoomDatabase.class) 58 | // Allowing main thread queries, just for testing. 59 | .allowMainThreadQueries() 60 | .build(); 61 | mWordDao = mDb.wordDao(); 62 | } 63 | 64 | @After 65 | public void closeDb() { 66 | mDb.close(); 67 | } 68 | 69 | @Test 70 | public void insertAndGetWord() throws Exception { 71 | Word word = new Word("word"); 72 | mWordDao.insert(word); 73 | List allWords = LiveDataTestUtil.getValue(mWordDao.getAlphabetizedWords()); 74 | assertEquals(allWords.get(0).getWord(), word.getWord()); 75 | } 76 | 77 | @Test 78 | public void getAllWords() throws Exception { 79 | Word word = new Word("aaa"); 80 | mWordDao.insert(word); 81 | Word word2 = new Word("bbb"); 82 | mWordDao.insert(word2); 83 | List allWords = LiveDataTestUtil.getValue(mWordDao.getAlphabetizedWords()); 84 | assertEquals(allWords.get(0).getWord(), word.getWord()); 85 | assertEquals(allWords.get(1).getWord(), word2.getWord()); 86 | } 87 | 88 | @Test 89 | public void deleteAll() throws Exception { 90 | Word word = new Word("word"); 91 | mWordDao.insert(word); 92 | Word word2 = new Word("word2"); 93 | mWordDao.insert(word2); 94 | mWordDao.deleteAll(); 95 | List allWords = LiveDataTestUtil.getValue(mWordDao.getAlphabetizedWords()); 96 | assertTrue(allWords.isEmpty()); 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 12 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /app/src/main/java/com/example/android/roomwordssample/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.example.android.roomwordssample; 2 | 3 | /* 4 | * Copyright (C) 2017 Google Inc. 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | import android.content.Intent; 20 | import android.os.Bundle; 21 | import android.view.View; 22 | import android.widget.Toast; 23 | 24 | import androidx.appcompat.app.AppCompatActivity; 25 | import androidx.lifecycle.ViewModelProvider; 26 | import androidx.recyclerview.widget.LinearLayoutManager; 27 | import androidx.recyclerview.widget.RecyclerView; 28 | 29 | import com.google.android.material.floatingactionbutton.FloatingActionButton; 30 | 31 | 32 | public class MainActivity extends AppCompatActivity { 33 | 34 | public static final int NEW_WORD_ACTIVITY_REQUEST_CODE = 1; 35 | 36 | private WordViewModel mWordViewModel; 37 | 38 | @Override 39 | protected void onCreate(Bundle savedInstanceState) { 40 | super.onCreate(savedInstanceState); 41 | setContentView(R.layout.activity_main); 42 | 43 | RecyclerView recyclerView = findViewById(R.id.recyclerview); 44 | final WordListAdapter adapter = new WordListAdapter(new WordListAdapter.WordDiff()); 45 | recyclerView.setAdapter(adapter); 46 | recyclerView.setLayoutManager(new LinearLayoutManager(this)); 47 | 48 | // Get a new or existing ViewModel from the ViewModelProvider. 49 | mWordViewModel = new ViewModelProvider(this).get(WordViewModel.class); 50 | 51 | // Add an observer on the LiveData returned by getAlphabetizedWords. 52 | // The onChanged() method fires when the observed data changes and the activity is 53 | // in the foreground. 54 | mWordViewModel.getAllWords().observe(this, words -> { 55 | // Update the cached copy of the words in the adapter. 56 | adapter.submitList(words); 57 | }); 58 | 59 | FloatingActionButton fab = findViewById(R.id.fab); 60 | fab.setOnClickListener(view -> { 61 | Intent intent = new Intent(MainActivity.this, NewWordActivity.class); 62 | startActivityForResult(intent, NEW_WORD_ACTIVITY_REQUEST_CODE); 63 | }); 64 | } 65 | 66 | public void onActivityResult(int requestCode, int resultCode, Intent data) { 67 | super.onActivityResult(requestCode, resultCode, data); 68 | 69 | if (requestCode == NEW_WORD_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) { 70 | Word word = new Word(data.getStringExtra(NewWordActivity.EXTRA_REPLY)); 71 | mWordViewModel.insert(word); 72 | } else { 73 | Toast.makeText( 74 | getApplicationContext(), 75 | R.string.empty_not_saved, 76 | Toast.LENGTH_LONG).show(); 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /app/src/main/java/com/example/android/roomwordssample/NewWordActivity.java: -------------------------------------------------------------------------------- 1 | package com.example.android.roomwordssample; 2 | 3 | /* 4 | * Copyright (C) 2017 Google Inc. 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | import android.content.Intent; 20 | import android.os.Bundle; 21 | import androidx.appcompat.app.AppCompatActivity; 22 | import android.text.TextUtils; 23 | import android.view.View; 24 | import android.widget.Button; 25 | import android.widget.EditText; 26 | 27 | /** 28 | * Activity for entering a word. 29 | */ 30 | 31 | public class NewWordActivity extends AppCompatActivity { 32 | 33 | public static final String EXTRA_REPLY = "com.example.android.wordlistsql.REPLY"; 34 | 35 | private EditText mEditWordView; 36 | 37 | @Override 38 | public void onCreate(Bundle savedInstanceState) { 39 | super.onCreate(savedInstanceState); 40 | setContentView(R.layout.activity_new_word); 41 | mEditWordView = findViewById(R.id.edit_word); 42 | 43 | final Button button = findViewById(R.id.button_save); 44 | button.setOnClickListener(view -> { 45 | Intent replyIntent = new Intent(); 46 | if (TextUtils.isEmpty(mEditWordView.getText())) { 47 | setResult(RESULT_CANCELED, replyIntent); 48 | } else { 49 | String word = mEditWordView.getText().toString(); 50 | replyIntent.putExtra(EXTRA_REPLY, word); 51 | setResult(RESULT_OK, replyIntent); 52 | } 53 | finish(); 54 | }); 55 | } 56 | } 57 | 58 | -------------------------------------------------------------------------------- /app/src/main/java/com/example/android/roomwordssample/Word.java: -------------------------------------------------------------------------------- 1 | package com.example.android.roomwordssample; 2 | 3 | /* 4 | * Copyright (C) 2017 Google Inc. 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | import androidx.room.ColumnInfo; 20 | import androidx.room.Entity; 21 | import androidx.room.PrimaryKey; 22 | import androidx.annotation.NonNull; 23 | 24 | /** 25 | * A basic class representing an entity that is a row in a one-column database table. 26 | * 27 | * @ Entity - You must annotate the class as an entity and supply a table name if not class name. 28 | * @ PrimaryKey - You must identify the primary key. 29 | * @ ColumnInfo - You must supply the column name if it is different from the variable name. 30 | * 31 | * See the documentation for the full rich set of annotations. 32 | * https://developer.android.com/topic/libraries/architecture/room.html 33 | */ 34 | 35 | @Entity(tableName = "word_table") 36 | public class Word { 37 | 38 | @PrimaryKey 39 | @NonNull 40 | @ColumnInfo(name = "word") 41 | private String mWord; 42 | 43 | public Word(@NonNull String word) { 44 | this.mWord = word; 45 | } 46 | 47 | @NonNull 48 | public String getWord() { 49 | return this.mWord; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /app/src/main/java/com/example/android/roomwordssample/WordDao.java: -------------------------------------------------------------------------------- 1 | package com.example.android.roomwordssample; 2 | 3 | /* 4 | * Copyright (C) 2017 Google Inc. 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | import androidx.lifecycle.LiveData; 20 | import androidx.room.Dao; 21 | import androidx.room.Insert; 22 | import androidx.room.OnConflictStrategy; 23 | import androidx.room.Query; 24 | 25 | import java.util.List; 26 | 27 | /** 28 | * The Room Magic is in this file, where you map a Java method call to an SQL query. 29 | * 30 | * When you are using complex data types, such as Date, you have to also supply type converters. 31 | * To keep this example basic, no types that require type converters are used. 32 | * See the documentation at 33 | * https://developer.android.com/topic/libraries/architecture/room.html#type-converters 34 | */ 35 | 36 | @Dao 37 | public interface WordDao { 38 | 39 | // LiveData is a data holder class that can be observed within a given lifecycle. 40 | // Always holds/caches latest version of data. Notifies its active observers when the 41 | // data has changed. Since we are getting all the contents of the database, 42 | // we are notified whenever any of the database contents have changed. 43 | @Query("SELECT * FROM word_table ORDER BY word ASC") 44 | LiveData> getAlphabetizedWords(); 45 | 46 | @Insert(onConflict = OnConflictStrategy.IGNORE) 47 | void insert(Word word); 48 | 49 | @Query("DELETE FROM word_table") 50 | void deleteAll(); 51 | } 52 | -------------------------------------------------------------------------------- /app/src/main/java/com/example/android/roomwordssample/WordListAdapter.java: -------------------------------------------------------------------------------- 1 | package com.example.android.roomwordssample; 2 | 3 | /* 4 | * Copyright (C) 2017 Google Inc. 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | import android.view.ViewGroup; 20 | 21 | import androidx.annotation.NonNull; 22 | import androidx.recyclerview.widget.DiffUtil; 23 | import androidx.recyclerview.widget.ListAdapter; 24 | 25 | 26 | public class WordListAdapter extends ListAdapter { 27 | 28 | public WordListAdapter(@NonNull DiffUtil.ItemCallback diffCallback) { 29 | super(diffCallback); 30 | } 31 | 32 | @Override 33 | public WordViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 34 | return WordViewHolder.create(parent); 35 | } 36 | 37 | @Override 38 | public void onBindViewHolder(WordViewHolder holder, int position) { 39 | Word current = getItem(position); 40 | holder.bind(current.getWord()); 41 | } 42 | 43 | static class WordDiff extends DiffUtil.ItemCallback { 44 | 45 | @Override 46 | public boolean areItemsTheSame(@NonNull Word oldItem, @NonNull Word newItem) { 47 | return oldItem == newItem; 48 | } 49 | 50 | @Override 51 | public boolean areContentsTheSame(@NonNull Word oldItem, @NonNull Word newItem) { 52 | return oldItem.getWord().equals(newItem.getWord()); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /app/src/main/java/com/example/android/roomwordssample/WordRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.android.roomwordssample; 2 | 3 | /* 4 | * Copyright (C) 2017 Google Inc. 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | import android.app.Application; 20 | import androidx.lifecycle.LiveData; 21 | 22 | import java.util.List; 23 | 24 | /** 25 | * Abstracted Repository as promoted by the Architecture Guide. 26 | * https://developer.android.com/topic/libraries/architecture/guide.html 27 | */ 28 | 29 | class WordRepository { 30 | 31 | private WordDao mWordDao; 32 | private LiveData> mAllWords; 33 | 34 | // Note that in order to unit test the WordRepository, you have to remove the Application 35 | // dependency. This adds complexity and much more code, and this sample is not about testing. 36 | // See the BasicSample in the android-architecture-components repository at 37 | // https://github.com/googlesamples 38 | WordRepository(Application application) { 39 | WordRoomDatabase db = WordRoomDatabase.getDatabase(application); 40 | mWordDao = db.wordDao(); 41 | mAllWords = mWordDao.getAlphabetizedWords(); 42 | } 43 | 44 | // Room executes all queries on a separate thread. 45 | // Observed LiveData will notify the observer when the data has changed. 46 | LiveData> getAllWords() { 47 | return mAllWords; 48 | } 49 | 50 | // You must call this on a non-UI thread or your app will throw an exception. Room ensures 51 | // that you're not doing any long running operations on the main thread, blocking the UI. 52 | void insert(Word word) { 53 | WordRoomDatabase.databaseWriteExecutor.execute(() -> { 54 | mWordDao.insert(word); 55 | }); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /app/src/main/java/com/example/android/roomwordssample/WordRoomDatabase.java: -------------------------------------------------------------------------------- 1 | package com.example.android.roomwordssample; 2 | 3 | /* 4 | * Copyright (C) 2017 Google Inc. 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | import android.content.Context; 20 | 21 | import androidx.annotation.NonNull; 22 | import androidx.room.Database; 23 | import androidx.room.Room; 24 | import androidx.room.RoomDatabase; 25 | import androidx.sqlite.db.SupportSQLiteDatabase; 26 | 27 | import java.util.concurrent.ExecutorService; 28 | import java.util.concurrent.Executors; 29 | 30 | /** 31 | * This is the backend. The database. This used to be done by the OpenHelper. 32 | * The fact that this has very few comments emphasizes its coolness. In a real 33 | * app, consider exporting the schema to help you with migrations. 34 | */ 35 | 36 | @Database(entities = {Word.class}, version = 1, exportSchema = false) 37 | abstract class WordRoomDatabase extends RoomDatabase { 38 | 39 | abstract WordDao wordDao(); 40 | 41 | // marking the instance as volatile to ensure atomic access to the variable 42 | private static volatile WordRoomDatabase INSTANCE; 43 | private static final int NUMBER_OF_THREADS = 4; 44 | static final ExecutorService databaseWriteExecutor = 45 | Executors.newFixedThreadPool(NUMBER_OF_THREADS); 46 | 47 | static WordRoomDatabase getDatabase(final Context context) { 48 | if (INSTANCE == null) { 49 | synchronized (WordRoomDatabase.class) { 50 | if (INSTANCE == null) { 51 | INSTANCE = Room.databaseBuilder(context.getApplicationContext(), 52 | WordRoomDatabase.class, "word_database") 53 | .addCallback(sRoomDatabaseCallback) 54 | .build(); 55 | } 56 | } 57 | } 58 | return INSTANCE; 59 | } 60 | 61 | /** 62 | * Override the onCreate method to populate the database. 63 | * For this sample, we clear the database every time it is created. 64 | */ 65 | private static RoomDatabase.Callback sRoomDatabaseCallback = new RoomDatabase.Callback() { 66 | @Override 67 | public void onCreate(@NonNull SupportSQLiteDatabase db) { 68 | super.onCreate(db); 69 | 70 | databaseWriteExecutor.execute(() -> { 71 | // Populate the database in the background. 72 | // If you want to start with more words, just add them. 73 | WordDao dao = INSTANCE.wordDao(); 74 | dao.deleteAll(); 75 | 76 | Word word = new Word("Hello"); 77 | dao.insert(word); 78 | word = new Word("World"); 79 | dao.insert(word); 80 | }); 81 | } 82 | }; 83 | } 84 | -------------------------------------------------------------------------------- /app/src/main/java/com/example/android/roomwordssample/WordViewHolder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2020 Google Inc. 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 | package com.example.android.roomwordssample; 18 | 19 | import android.view.LayoutInflater; 20 | import android.view.View; 21 | import android.view.ViewGroup; 22 | import android.widget.TextView; 23 | 24 | import androidx.recyclerview.widget.RecyclerView; 25 | 26 | class WordViewHolder extends RecyclerView.ViewHolder { 27 | private final TextView wordItemView; 28 | 29 | private WordViewHolder(View itemView) { 30 | super(itemView); 31 | wordItemView = itemView.findViewById(R.id.textView); 32 | } 33 | 34 | public void bind(String text) { 35 | wordItemView.setText(text); 36 | } 37 | 38 | static WordViewHolder create(ViewGroup parent) { 39 | View view = LayoutInflater.from(parent.getContext()) 40 | .inflate(R.layout.recyclerview_item, parent, false); 41 | return new WordViewHolder(view); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /app/src/main/java/com/example/android/roomwordssample/WordViewModel.java: -------------------------------------------------------------------------------- 1 | package com.example.android.roomwordssample; 2 | 3 | /* 4 | * Copyright (C) 2017 Google Inc. 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | import android.app.Application; 20 | import androidx.lifecycle.AndroidViewModel; 21 | import androidx.lifecycle.LiveData; 22 | 23 | import java.util.List; 24 | 25 | /** 26 | * View Model to keep a reference to the word repository and 27 | * an up-to-date list of all words. 28 | */ 29 | 30 | public class WordViewModel extends AndroidViewModel { 31 | 32 | private WordRepository mRepository; 33 | // Using LiveData and caching what getAlphabetizedWords returns has several benefits: 34 | // - We can put an observer on the data (instead of polling for changes) and only update the 35 | // the UI when the data actually changes. 36 | // - Repository is completely separated from the UI through the ViewModel. 37 | private final LiveData> mAllWords; 38 | 39 | public WordViewModel(Application application) { 40 | super(application); 41 | mRepository = new WordRepository(application); 42 | mAllWords = mRepository.getAllWords(); 43 | } 44 | 45 | LiveData> getAllWords() { 46 | return mAllWords; 47 | } 48 | 49 | void insert(Word word) { 50 | mRepository.insert(word); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_add_black_24dp.xml: -------------------------------------------------------------------------------- 1 | 6 | 9 | 10 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 12 | 17 | 22 | 27 | 32 | 37 | 42 | 47 | 52 | 57 | 62 | 67 | 72 | 77 | 82 | 87 | 92 | 97 | 102 | 107 | 112 | 113 | 114 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16 | 17 | 20 | 21 | 28 | 29 | 39 | 40 | 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_new_word.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16 | 17 | 21 | 22 | 32 | 33 |