11 |
12 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/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 [yyyy] [name of copyright owner]
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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
Mini Brother Eye
7 |
8 | Mini Brother Eye is a small demo app that tries to follow Modern Android Development best practices
9 | and uses the latest tools and Open Source Libraries.
10 |
11 | It is supposed to be a smaller version of DC's [Brother Eye](https://dc.fandom.com/wiki/Brother_Eye_(New_Earth)).
12 |
13 |
14 |
15 |
16 |
17 | ## Techstack and Open Source libraries
18 |
19 | ### Code
20 |
21 | - Minimum SDK Level 19
22 | - [Kotlin Coroutines](https://github.com/Kotlin/kotlinx.coroutines) for asynchronous operations.
23 | - [Retrofit2](https://github.com/square/retrofit) to make HTTP calls to the REST API.
24 | - [GSON](https://github.com/google/gson) to deserialize JSON requests.
25 | - [Coil](https://github.com/coil-kt/coil) for image loading.
26 | - [Material Components](https://github.com/material-components/material-components-android)
27 | to display Material Design Components.
28 | - [Material Motion](https://material.io/develop/android/theming/motion/) - transitions for navigation.
29 | - Android Jetpack
30 | - [DataBinding](https://developer.android.com/topic/libraries/data-binding)
31 | - [LiveData](https://developer.android.com/topic/libraries/architecture/livedata)
32 | - [Navigation Component](https://developer.android.com/guide/navigation)
33 | - [Paging Library 3](https://developer.android.com/topic/libraries/architecture/paging) (alpha)
34 | - [Room](https://developer.android.com/topic/libraries/architecture/room)
35 | - [ViewModel](https://developer.android.com/topic/libraries/architecture/viewmodel)
36 | - [Hilt](https://developer.android.com/training/dependency-injection/hilt-android) (alpha) for
37 | Dependency Injection
38 | - [RamiJ3mli/PercentageChartView](https://github.com/RamiJ3mli/PercentageChartView) to display
39 | progress information
40 |
41 | ### Tests
42 |
43 | - [Robolectric](https://github.com/robolectric/robolectric) and
44 | [AndroidX Test libraries](https://developer.android.com/training/testing) for Unit Testing.
45 | - [Mockito](https://github.com/mockito/mockito) to create the mocks used in the Unit Tests.
46 | - [MockWebServer](https://github.com/square/okhttp/tree/master/mockwebserver) to mock web server
47 | calls.
48 |
49 |
50 | ## License
51 |
52 | ```
53 | Copyright 2020 Rosário Pereira Fernandes
54 |
55 | Licensed under the Apache License, Version 2.0 (the "License");
56 | you may not use this file except in compliance with the License.
57 | You may obtain a copy of the License at
58 |
59 | https://www.apache.org/licenses/LICENSE-2.0
60 |
61 | Unless required by applicable law or agreed to in writing, software
62 | distributed under the License is distributed on an "AS IS" BASIS,
63 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
64 | See the License for the specific language governing permissions and
65 | limitations under the License.
66 | ```
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/app/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | id("com.android.application")
3 | id("dagger.hilt.android.plugin")
4 | kotlin("android")
5 | kotlin("kapt")
6 | }
7 |
8 | android {
9 | compileSdkVersion(30)
10 | buildToolsVersion("30.0.0")
11 |
12 | defaultConfig {
13 | applicationId = "io.github.rosariopfernandes.minibrothereye"
14 | minSdkVersion(19)
15 | targetSdkVersion(30)
16 | versionCode = 1
17 | versionName = "1.0"
18 |
19 | testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
20 | }
21 |
22 | buildTypes {
23 | getByName("release") {
24 | isMinifyEnabled = false
25 | proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
26 | }
27 | }
28 | buildFeatures {
29 | dataBinding = true
30 | }
31 | compileOptions {
32 | sourceCompatibility = JavaVersion.VERSION_1_8
33 | targetCompatibility = JavaVersion.VERSION_1_8
34 | }
35 | kotlinOptions {
36 | jvmTarget = "1.8"
37 | }
38 | }
39 |
40 | dependencies {
41 | val kotlinVersion = rootProject.extra.get("kotlin_version") as String
42 | val hiltVersion = rootProject.extra.get("hilt_version") as String
43 |
44 | implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar"))))
45 | implementation("org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion")
46 | implementation("androidx.core:core-ktx:1.3.0")
47 | implementation("androidx.appcompat:appcompat:1.1.0")
48 | implementation("com.google.android.material:material:1.2.0-beta01")
49 | implementation("androidx.constraintlayout:constraintlayout:1.1.3")
50 | implementation("androidx.navigation:navigation-fragment-ktx:2.2.2")
51 | implementation("androidx.navigation:navigation-ui-ktx:2.2.2")
52 | implementation("androidx.lifecycle:lifecycle-livedata-ktx:2.2.0")
53 | implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0")
54 | implementation("androidx.paging:paging-runtime-ktx:3.0.0-alpha02")
55 | implementation("androidx.preference:preference-ktx:1.1.1")
56 |
57 | // Room (Offline Persistence)
58 | implementation("androidx.room:room-runtime:2.2.5")
59 | implementation("androidx.room:room-ktx:2.2.5") // support for coroutines
60 | kapt("androidx.room:room-compiler:2.2.5")
61 |
62 | // Retrofit (Networking)
63 | implementation("com.squareup.retrofit2:retrofit:2.9.0")
64 | implementation("com.squareup.retrofit2:converter-gson:2.9.0")
65 |
66 | // Coil (Image Loading)
67 | implementation("io.coil-kt:coil:0.11.0")
68 |
69 | // Coroutines (Asynchronous Operations)
70 | implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.6")
71 |
72 | // Hilt (Dependency Injection)
73 | implementation("com.google.dagger:hilt-android:$hiltVersion")
74 | kapt("com.google.dagger:hilt-android-compiler:$hiltVersion")
75 | implementation("androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha01")
76 | kapt("androidx.hilt:hilt-compiler:1.0.0-alpha01")
77 |
78 | implementation("com.ramijemli.percentagechartview:percentagechartview:0.3.1")
79 |
80 | // For Unit Tests
81 | testImplementation("junit:junit:4.12")
82 | testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.3.3")
83 | testImplementation("org.mockito:mockito-core:3.3.3")
84 | testImplementation("androidx.arch.core:core-testing:2.1.0")
85 | testImplementation("androidx.test:core-ktx:1.2.0")
86 | testImplementation("androidx.test.ext:junit-ktx:1.1.1")
87 | testImplementation("org.robolectric:robolectric:4.3.1")
88 | testImplementation("com.squareup.okhttp3:mockwebserver:4.7.2")
89 |
90 | androidTestImplementation("androidx.test.ext:junit:1.1.1")
91 | androidTestImplementation("androidx.test.espresso:espresso-core:3.2.0")
92 |
93 | }
--------------------------------------------------------------------------------
/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
--------------------------------------------------------------------------------
/app/src/androidTest/java/io/github/rosariopfernandes/minibrothereye/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package io.github.rosariopfernandes.minibrothereye
2 |
3 | import androidx.test.platform.app.InstrumentationRegistry
4 | import androidx.test.ext.junit.runners.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22 | assertEquals("io.github.rosariopfernandes.minibrothereye", appContext.packageName)
23 | }
24 | }
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
15 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/app/src/main/java/io/github/rosariopfernandes/minibrothereye/BrotherEyeApplication.kt:
--------------------------------------------------------------------------------
1 | package io.github.rosariopfernandes.minibrothereye
2 |
3 | import android.app.Application
4 | import androidx.appcompat.app.AppCompatDelegate
5 | import androidx.preference.PreferenceManager
6 | import dagger.hilt.android.HiltAndroidApp
7 | import io.github.rosariopfernandes.minibrothereye.util.PREF_DARK_THEME
8 |
9 | @HiltAndroidApp
10 | class BrotherEyeApplication : Application() {
11 |
12 | override fun onCreate() {
13 | super.onCreate()
14 |
15 | val preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext)
16 | val mode = preferences.getBoolean(PREF_DARK_THEME, false)
17 | if (mode) {
18 | AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
19 | } else {
20 | AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY)
21 | }
22 | }
23 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/rosariopfernandes/minibrothereye/data/AppDatabase.kt:
--------------------------------------------------------------------------------
1 | package io.github.rosariopfernandes.minibrothereye.data
2 |
3 | import androidx.room.Database
4 | import androidx.room.RoomDatabase
5 | import androidx.room.TypeConverters
6 | import io.github.rosariopfernandes.minibrothereye.model.Character
7 | import io.github.rosariopfernandes.minibrothereye.util.StringListConverters
8 |
9 | @Database(entities = [Character::class], version = 2, exportSchema = false)
10 | @TypeConverters(StringListConverters::class)
11 | abstract class AppDatabase : RoomDatabase() {
12 | abstract fun characterDao(): CharacterDao
13 | }
14 |
--------------------------------------------------------------------------------
/app/src/main/java/io/github/rosariopfernandes/minibrothereye/data/CharacterDao.kt:
--------------------------------------------------------------------------------
1 | package io.github.rosariopfernandes.minibrothereye.data
2 |
3 | import androidx.room.Dao
4 | import androidx.room.Insert
5 | import androidx.room.OnConflictStrategy
6 | import androidx.room.Query
7 | import io.github.rosariopfernandes.minibrothereye.model.Character
8 |
9 | @Dao
10 | interface CharacterDao {
11 |
12 | @Query("SELECT * FROM characters LIMIT 4 OFFSET :offset")
13 | suspend fun get4Characters(offset: Int): List
14 |
15 | @Query("SELECT * FROM characters WHERE id=:id")
16 | suspend fun getInfo(id: Int): Character?
17 |
18 | @Insert(onConflict = OnConflictStrategy.REPLACE)
19 | suspend fun insertCharacter(character: Character)
20 |
21 | @Insert(onConflict = OnConflictStrategy.REPLACE)
22 | suspend fun insertAll(characters: List)
23 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/rosariopfernandes/minibrothereye/data/CharacterPagingSource.kt:
--------------------------------------------------------------------------------
1 | package io.github.rosariopfernandes.minibrothereye.data
2 |
3 | import androidx.paging.PagingSource
4 | import io.github.rosariopfernandes.minibrothereye.model.Character
5 | import io.github.rosariopfernandes.minibrothereye.repository.CharacterRepository
6 | import java.net.UnknownHostException
7 |
8 | class CharacterPagingSource(
9 | private val characterRepository: CharacterRepository
10 | ) : PagingSource() {
11 | override suspend fun load(params: LoadParams): LoadResult {
12 | return try {
13 | val nextPageNumber = params.key ?: 0
14 | val characterPage = characterRepository.fetchCharacterPage(nextPageNumber)
15 | LoadResult.Page(
16 | data = characterPage,
17 | prevKey = null,
18 | nextKey = nextPageNumber + 4
19 | )
20 | } catch (e: UnknownHostException) {
21 | // Unable to connect to the network
22 | LoadResult.Error(e)
23 | }
24 | }
25 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/rosariopfernandes/minibrothereye/di/LocalDatabaseModule.kt:
--------------------------------------------------------------------------------
1 | package io.github.rosariopfernandes.minibrothereye.di
2 |
3 | import android.app.Application
4 | import androidx.room.Room
5 | import dagger.Module
6 | import dagger.Provides
7 | import dagger.hilt.InstallIn
8 | import dagger.hilt.android.components.ApplicationComponent
9 | import io.github.rosariopfernandes.minibrothereye.data.AppDatabase
10 | import io.github.rosariopfernandes.minibrothereye.data.CharacterDao
11 | import javax.inject.Singleton
12 |
13 | @Module
14 | @InstallIn(ApplicationComponent::class)
15 | object LocalDatabaseModule {
16 |
17 | @Provides
18 | @Singleton
19 | fun provideAppDatabase(application: Application): AppDatabase {
20 | return Room.databaseBuilder(application, AppDatabase::class.java, "characters-db")
21 | .fallbackToDestructiveMigration() // Recreate tables if no migrations were found
22 | .build()
23 | }
24 |
25 | @Provides
26 | fun provideCharacterDao(appDatabase: AppDatabase): CharacterDao {
27 | return appDatabase.characterDao()
28 | }
29 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/rosariopfernandes/minibrothereye/di/NetworkModule.kt:
--------------------------------------------------------------------------------
1 | package io.github.rosariopfernandes.minibrothereye.di
2 |
3 | import dagger.Module
4 | import dagger.Provides
5 | import dagger.hilt.InstallIn
6 | import dagger.hilt.android.components.ApplicationComponent
7 | import io.github.rosariopfernandes.minibrothereye.network.CharacterService
8 | import io.github.rosariopfernandes.minibrothereye.util.API_BASE_URL
9 | import retrofit2.Retrofit
10 | import retrofit2.converter.gson.GsonConverterFactory
11 |
12 | @Module
13 | @InstallIn(ApplicationComponent::class)
14 | object NetworkModule {
15 |
16 | @Provides
17 | fun provideCharacterService(): CharacterService {
18 | val retrofit = Retrofit.Builder()
19 | .baseUrl(API_BASE_URL)
20 | .addConverterFactory(GsonConverterFactory.create())
21 | .build()
22 | return retrofit.create(CharacterService::class.java)
23 | }
24 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/rosariopfernandes/minibrothereye/di/RepositoryModule.kt:
--------------------------------------------------------------------------------
1 | package io.github.rosariopfernandes.minibrothereye.di
2 |
3 | import dagger.Module
4 | import dagger.Provides
5 | import dagger.hilt.InstallIn
6 | import dagger.hilt.android.components.ActivityRetainedComponent
7 | import dagger.hilt.android.scopes.ActivityRetainedScoped
8 | import io.github.rosariopfernandes.minibrothereye.data.CharacterDao
9 | import io.github.rosariopfernandes.minibrothereye.network.CharacterService
10 | import io.github.rosariopfernandes.minibrothereye.repository.CharacterRepository
11 | import io.github.rosariopfernandes.minibrothereye.repository.CharacterRepositoryImpl
12 |
13 | @Module
14 | @InstallIn(ActivityRetainedComponent::class)
15 | object RepositoryModule {
16 |
17 | @Provides
18 | @ActivityRetainedScoped
19 | fun provideCharacterRepository(
20 | characterDao: CharacterDao,
21 | characterService: CharacterService
22 | ): CharacterRepository {
23 | return CharacterRepositoryImpl(characterDao, characterService)
24 | }
25 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/rosariopfernandes/minibrothereye/model/Character.kt:
--------------------------------------------------------------------------------
1 | package io.github.rosariopfernandes.minibrothereye.model
2 |
3 | import androidx.room.ColumnInfo
4 | import androidx.room.Embedded
5 | import androidx.room.Entity
6 | import androidx.room.PrimaryKey
7 |
8 | @Entity(tableName = "characters")
9 | data class Character(
10 | @PrimaryKey val id: Int = 1,
11 | val name: String = "",
12 | @Embedded val powerstats: PowerStats = PowerStats(),
13 | @Embedded val appearance: Appearance = Appearance(),
14 | @Embedded val biography: Biography = Biography(),
15 | @Embedded val work: Work = Work(),
16 | @Embedded val connections: Connections = Connections(),
17 | @Embedded val images: Images = Images()
18 | )
19 |
20 | data class PowerStats(
21 | val intelligence: Int = 0,
22 | val strength: Int = 0,
23 | val speed: Int = 0,
24 | val durability: Int = 0,
25 | val power: Int = 0,
26 | val combat: Int = 0
27 | )
28 |
29 | data class Appearance(
30 | val gender: String = "",
31 | val height: List = listOf(),
32 | val weight: List = listOf()
33 | )
34 |
35 | data class Biography(
36 | val fullName: String = "-",
37 | val alterEgos: String = "No alter egos found.",
38 | val aliases: List = listOf(),
39 | val placeOfBirth: String = "-",
40 | val firstAppearance: String = "-",
41 | val alignment: String = ""
42 | )
43 |
44 | data class Work(val occupation: String = "-", val base: String = "-")
45 |
46 | data class Connections(val groupAffiliation: String = "-", val relatives: String = "-")
47 |
48 | data class Images(
49 | @ColumnInfo(name = "image_url") val md: String = ""
50 | )
51 |
--------------------------------------------------------------------------------
/app/src/main/java/io/github/rosariopfernandes/minibrothereye/network/CharacterService.kt:
--------------------------------------------------------------------------------
1 | package io.github.rosariopfernandes.minibrothereye.network
2 |
3 | import io.github.rosariopfernandes.minibrothereye.model.Character
4 | import retrofit2.http.GET
5 | import retrofit2.http.Path
6 |
7 | interface CharacterService {
8 |
9 | @GET("all/")
10 | suspend fun getCharacterList(): List
11 |
12 | @GET("id/{id}/")
13 | suspend fun getCharacterInfo(@Path("id") id: Int): Character
14 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/rosariopfernandes/minibrothereye/repository/CharacterRepository.kt:
--------------------------------------------------------------------------------
1 | package io.github.rosariopfernandes.minibrothereye.repository
2 |
3 | import io.github.rosariopfernandes.minibrothereye.model.Character
4 |
5 | interface CharacterRepository {
6 | suspend fun fetchCharacterPage(offset: Int): List
7 | suspend fun fetchCharacterInfo(characterId: Int): Character
8 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/rosariopfernandes/minibrothereye/repository/CharacterRepositoryImpl.kt:
--------------------------------------------------------------------------------
1 | package io.github.rosariopfernandes.minibrothereye.repository
2 |
3 | import io.github.rosariopfernandes.minibrothereye.data.CharacterDao
4 | import io.github.rosariopfernandes.minibrothereye.model.Character
5 | import io.github.rosariopfernandes.minibrothereye.network.CharacterService
6 | import javax.inject.Inject
7 |
8 | class CharacterRepositoryImpl @Inject constructor(
9 | private val characterDao: CharacterDao,
10 | private val characterService: CharacterService
11 | ) : CharacterRepository {
12 |
13 | /**
14 | * Fetches 4 characters
15 | */
16 | override suspend fun fetchCharacterPage(offset: Int): List {
17 | val charactersList: List
18 | val cachedCharacters = characterDao.get4Characters(offset)
19 | if (cachedCharacters.isEmpty()) {
20 | charactersList = characterService.getCharacterList()
21 | characterDao.insertAll(charactersList)
22 | }
23 | return characterDao.get4Characters(offset)
24 | }
25 |
26 | override suspend fun fetchCharacterInfo(characterId: Int): Character {
27 | val characterInfo: Character
28 | val cachedCharacter = characterDao.getInfo(characterId)
29 | if (cachedCharacter != null) {
30 | characterInfo = cachedCharacter
31 | } else {
32 | characterInfo = characterService.getCharacterInfo(characterId)
33 | characterDao.insertCharacter(characterInfo)
34 | }
35 | return characterInfo
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/app/src/main/java/io/github/rosariopfernandes/minibrothereye/ui/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package io.github.rosariopfernandes.minibrothereye.ui
2 |
3 | import android.content.SharedPreferences
4 | import android.os.Build
5 | import android.os.Bundle
6 | import androidx.appcompat.app.AppCompatActivity
7 | import android.view.Menu
8 | import android.view.MenuItem
9 | import androidx.appcompat.app.AppCompatDelegate
10 | import androidx.core.content.ContextCompat
11 | import androidx.core.content.edit
12 | import androidx.preference.PreferenceManager
13 | import dagger.hilt.android.AndroidEntryPoint
14 | import io.github.rosariopfernandes.minibrothereye.R
15 | import io.github.rosariopfernandes.minibrothereye.databinding.ActivityMainBinding
16 | import io.github.rosariopfernandes.minibrothereye.util.PREF_DARK_THEME
17 |
18 | @AndroidEntryPoint
19 | class MainActivity : AppCompatActivity() {
20 | private lateinit var preferences: SharedPreferences
21 | private var darkModeEnabled = false
22 |
23 | override fun onCreate(savedInstanceState: Bundle?) {
24 | super.onCreate(savedInstanceState)
25 | val binding = ActivityMainBinding.inflate(layoutInflater)
26 | setContentView(binding.root)
27 | setSupportActionBar(binding.toolbar)
28 |
29 | preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext)
30 | }
31 |
32 | override fun onCreateOptionsMenu(menu: Menu): Boolean {
33 | // Inflate the menu; this adds items to the action bar if it is present.
34 | menuInflater.inflate(R.menu.menu_main, menu)
35 | return true
36 | }
37 |
38 | override fun onPrepareOptionsMenu(menu: Menu): Boolean {
39 | val menuItem = menu.findItem(R.id.action_dark_theme_toggle)
40 | darkModeEnabled = preferences.getBoolean(PREF_DARK_THEME, false)
41 | if (darkModeEnabled) {
42 | menuItem.icon =
43 | ContextCompat.getDrawable(this,
44 | R.drawable.ic_brightness_high_white_24dp
45 | )
46 | menuItem.title = getString(R.string.light_theme)
47 | } else {
48 | menuItem.icon =
49 | ContextCompat.getDrawable(this,
50 | R.drawable.ic_brightness_medium_white_24dp
51 | )
52 | menuItem.title = getString(R.string.dark_theme)
53 | }
54 | return true
55 | }
56 |
57 | override fun onOptionsItemSelected(item: MenuItem): Boolean {
58 | // Handle action bar item clicks here. The action bar will
59 | // automatically handle clicks on the Home/Up button, so long
60 | // as you specify a parent activity in AndroidManifest.xml.
61 | return when (item.itemId) {
62 | R.id.action_dark_theme_toggle -> {
63 | darkModeEnabled = preferences.getBoolean(PREF_DARK_THEME, false)
64 | darkModeEnabled = !darkModeEnabled
65 | preferences.edit {
66 | putBoolean(PREF_DARK_THEME, darkModeEnabled)
67 | }
68 | if (darkModeEnabled) {
69 | AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
70 | } else {
71 | AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY)
72 | }
73 | recreate()
74 | true
75 | }
76 | else -> super.onOptionsItemSelected(item)
77 | }
78 | }
79 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/rosariopfernandes/minibrothereye/ui/characterinfo/CharacterInfoFragment.kt:
--------------------------------------------------------------------------------
1 | package io.github.rosariopfernandes.minibrothereye.ui.characterinfo
2 |
3 | import android.os.Bundle
4 | import androidx.fragment.app.Fragment
5 | import android.view.LayoutInflater
6 | import android.view.View
7 | import android.view.ViewGroup
8 | import androidx.core.content.ContextCompat
9 | import androidx.core.view.ViewCompat
10 | import androidx.fragment.app.viewModels
11 | import androidx.lifecycle.Observer
12 | import com.google.android.material.snackbar.Snackbar
13 | import com.google.android.material.transition.MaterialContainerTransform
14 | import dagger.hilt.android.AndroidEntryPoint
15 | import io.github.rosariopfernandes.minibrothereye.R
16 | import io.github.rosariopfernandes.minibrothereye.databinding.FragmentCharacterInfoBinding
17 |
18 | /**
19 | * A simple [Fragment] subclass as the second destination in the navigation.
20 | */
21 | @AndroidEntryPoint
22 | class CharacterInfoFragment : Fragment() {
23 |
24 | private val viewModel: CharacterInfoViewModel by viewModels()
25 |
26 | private var _binding: FragmentCharacterInfoBinding? = null
27 | private val binding get() = _binding!!
28 |
29 | override fun onCreate(savedInstanceState: Bundle?) {
30 | super.onCreate(savedInstanceState)
31 |
32 | sharedElementEnterTransition = MaterialContainerTransform().apply {
33 | fadeMode = MaterialContainerTransform.FADE_MODE_THROUGH
34 | scrimColor = ContextCompat.getColor(requireContext(), android.R.color.transparent)
35 | }
36 | }
37 |
38 | override fun onCreateView(
39 | inflater: LayoutInflater, container: ViewGroup?,
40 | savedInstanceState: Bundle?
41 | ): View? {
42 | _binding = FragmentCharacterInfoBinding.inflate(inflater, container, false)
43 | val args = requireArguments()
44 | ViewCompat.setTransitionName(binding.root, "${args.getInt("id")}")
45 | return binding.root
46 | }
47 |
48 | override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
49 | super.onViewCreated(view, savedInstanceState)
50 |
51 | val characterId = requireArguments().getInt("id")
52 | viewModel.fetchCharacterInfo(characterId)
53 |
54 | with (binding) {
55 | lifecycleOwner = viewLifecycleOwner
56 | this.viewmodel = viewModel
57 | }
58 | viewModel.exception.observe(viewLifecycleOwner, Observer { exception ->
59 | exception?.let {
60 | it.printStackTrace()
61 | Snackbar.make(view, R.string.error_cant_load_data, Snackbar.LENGTH_INDEFINITE)
62 | .show()
63 | }
64 | })
65 | }
66 |
67 | override fun onDestroyView() {
68 | super.onDestroyView()
69 | _binding = null
70 | }
71 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/rosariopfernandes/minibrothereye/ui/characterinfo/CharacterInfoViewModel.kt:
--------------------------------------------------------------------------------
1 | package io.github.rosariopfernandes.minibrothereye.ui.characterinfo
2 |
3 | import androidx.hilt.lifecycle.ViewModelInject
4 | import androidx.lifecycle.LiveData
5 | import androidx.lifecycle.MutableLiveData
6 | import androidx.lifecycle.ViewModel
7 | import androidx.lifecycle.viewModelScope
8 | import io.github.rosariopfernandes.minibrothereye.model.Character
9 | import io.github.rosariopfernandes.minibrothereye.repository.CharacterRepository
10 | import kotlinx.coroutines.launch
11 |
12 | class CharacterInfoViewModel @ViewModelInject constructor(
13 | private val repository: CharacterRepository
14 | ) : ViewModel() {
15 |
16 | private val _isLoading = MutableLiveData()
17 | val isLoading: LiveData
18 | get() = _isLoading
19 |
20 | private val _characterInfo = MutableLiveData()
21 | val characterInfo: LiveData
22 | get() = _characterInfo
23 |
24 | private val _exception = MutableLiveData()
25 | val exception: LiveData
26 | get() = _exception
27 |
28 | init {
29 | _characterInfo.value = Character()
30 | _isLoading.value = false
31 | _exception.value = null
32 | }
33 |
34 | fun fetchCharacterInfo(characterId: Int) {
35 | viewModelScope.launch {
36 | // There's no point in fetching again if it's already loading
37 | if (_isLoading.value == false) {
38 | _isLoading.value = true
39 | try {
40 | val character = repository.fetchCharacterInfo(characterId)
41 | _characterInfo.value = character
42 | } catch (e: Exception) {
43 | e.printStackTrace()
44 | _exception.value = e
45 | }
46 | _isLoading.value = false
47 | }
48 | }
49 | }
50 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/rosariopfernandes/minibrothereye/ui/characterinfo/PowerStatAdapter.kt:
--------------------------------------------------------------------------------
1 | package io.github.rosariopfernandes.minibrothereye.ui.characterinfo
2 |
3 | import android.os.Build
4 | import android.view.LayoutInflater
5 | import android.view.View
6 | import android.view.ViewGroup
7 | import android.widget.ProgressBar
8 | import android.widget.TextView
9 | import androidx.core.content.ContextCompat
10 | import androidx.recyclerview.widget.RecyclerView
11 | import com.ramijemli.percentagechartview.PercentageChartView
12 | import io.github.rosariopfernandes.minibrothereye.R
13 | import io.github.rosariopfernandes.minibrothereye.model.PowerStats
14 |
15 | class PowerStatAdapter(
16 | private val powerStats: PowerStats
17 | ) : RecyclerView.Adapter() {
18 |
19 | override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PowerStatViewHolder {
20 | val view = LayoutInflater.from(parent.context)
21 | .inflate(R.layout.item_powerstat, parent, false)
22 | return PowerStatViewHolder(view)
23 | }
24 |
25 | override fun getItemCount() = 6
26 |
27 | override fun onBindViewHolder(holder: PowerStatViewHolder, position: Int) {
28 | when (position) {
29 | 0 -> holder.bindTo(R.string.label_intelligence, powerStats.intelligence, R.color.colorPurple)
30 | 1 -> holder.bindTo(R.string.label_strength, powerStats.strength, R.color.colorRed)
31 | 2 -> holder.bindTo(R.string.label_speed, powerStats.speed, R.color.colorAmber)
32 | 3 -> holder.bindTo(R.string.label_durability, powerStats.durability, R.color.colorYellow)
33 | 4 -> holder.bindTo(R.string.label_power, powerStats.power, R.color.colorGreen)
34 | 5 -> holder.bindTo(R.string.label_combat, powerStats.combat, R.color.colorIndigo)
35 | }
36 | }
37 |
38 | class PowerStatViewHolder(v: View) : RecyclerView.ViewHolder(v) {
39 | private val pbStat = v.findViewById(R.id.pbStat)
40 | private val tvStatLabel = v.findViewById(R.id.tvStatLabel)
41 |
42 | fun bindTo(labelResId: Int, stat: Int, colorResId: Int) {
43 | tvStatLabel.setText(labelResId)
44 | pbStat.setProgress(stat.toFloat(), true)
45 | pbStat.progressColor = ContextCompat.getColor(pbStat.context, colorResId)
46 | }
47 | }
48 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/rosariopfernandes/minibrothereye/ui/list/CharacterAdapter.kt:
--------------------------------------------------------------------------------
1 | package io.github.rosariopfernandes.minibrothereye.ui.list
2 |
3 | import android.view.LayoutInflater
4 | import android.view.ViewGroup
5 | import androidx.core.view.ViewCompat
6 | import androidx.navigation.Navigator
7 | import androidx.navigation.fragment.FragmentNavigatorExtras
8 | import androidx.paging.PagingDataAdapter
9 | import androidx.recyclerview.widget.DiffUtil
10 | import androidx.recyclerview.widget.RecyclerView
11 | import io.github.rosariopfernandes.minibrothereye.databinding.ItemCharacterBinding
12 | import io.github.rosariopfernandes.minibrothereye.model.Character
13 |
14 | class CharacterAdapter(
15 | private val clickListener: (CharacterListItem, Navigator.Extras) -> Unit
16 | ) : PagingDataAdapter(DIFF_CALLBACK) {
17 |
18 | override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CharacterViewHolder {
19 | val binding = ItemCharacterBinding.inflate(
20 | LayoutInflater.from(parent.context),
21 | parent,
22 | false
23 | )
24 | return CharacterViewHolder(binding)
25 | }
26 |
27 | override fun onBindViewHolder(holder: CharacterViewHolder, position: Int) {
28 | val character = getItem(position)
29 | character?.let {
30 | val characterItem = CharacterListItem(
31 | id = character.id,
32 | name = character.name,
33 | photoUrl = character.images.md
34 | )
35 | holder.bindTo(characterItem, clickListener)
36 | }
37 | }
38 |
39 | class CharacterViewHolder(
40 | private val binding: ItemCharacterBinding
41 | ) : RecyclerView.ViewHolder(binding.root) {
42 |
43 | fun bindTo(
44 | item: CharacterListItem,
45 | clickListener: (CharacterListItem, Navigator.Extras) -> Unit
46 | ) {
47 | binding.character = item
48 | ViewCompat.setTransitionName(binding.root, "${item.id}")
49 | itemView.setOnClickListener {
50 | val extras = FragmentNavigatorExtras(
51 | binding.root to "${item.id}"
52 | )
53 | clickListener(item, extras)
54 | }
55 | }
56 | }
57 |
58 | /**
59 | * Helper class to represent the character displayed on the UI
60 | */
61 | data class CharacterListItem(val id: Int, val photoUrl: String, val name: String)
62 |
63 | companion object {
64 | val DIFF_CALLBACK = object: DiffUtil.ItemCallback() {
65 | override fun areItemsTheSame(
66 | oldItem: Character,
67 | newItem: Character
68 | ) = oldItem.id == newItem.id
69 |
70 | override fun areContentsTheSame(
71 | oldItem: Character,
72 | newItem: Character
73 | ) = oldItem == newItem
74 | }
75 | }
76 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/rosariopfernandes/minibrothereye/ui/list/ListFragment.kt:
--------------------------------------------------------------------------------
1 | package io.github.rosariopfernandes.minibrothereye.ui.list
2 |
3 | import android.os.Bundle
4 | import androidx.fragment.app.Fragment
5 | import android.view.LayoutInflater
6 | import android.view.View
7 | import android.view.ViewGroup
8 | import androidx.core.os.bundleOf
9 | import androidx.fragment.app.viewModels
10 | import androidx.lifecycle.lifecycleScope
11 | import androidx.navigation.fragment.findNavController
12 | import dagger.hilt.android.AndroidEntryPoint
13 | import io.github.rosariopfernandes.minibrothereye.R
14 | import io.github.rosariopfernandes.minibrothereye.databinding.FragmentListBinding
15 | import kotlinx.coroutines.flow.collectLatest
16 | import kotlinx.coroutines.launch
17 |
18 | /**
19 | * A simple [Fragment] subclass as the default destination in the navigation.
20 | */
21 | @AndroidEntryPoint
22 | class ListFragment : Fragment() {
23 |
24 | private val viewModel: ListViewModel by viewModels()
25 |
26 | private var _binding: FragmentListBinding? = null
27 | private val binding get() = _binding!!
28 |
29 | override fun onCreateView(
30 | inflater: LayoutInflater, container: ViewGroup?,
31 | savedInstanceState: Bundle?
32 | ): View? {
33 | _binding = FragmentListBinding.inflate(inflater, container, false)
34 | return binding.root
35 | }
36 |
37 | override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
38 | super.onViewCreated(view, savedInstanceState)
39 |
40 | val charactersAdapter = CharacterAdapter { item, extras ->
41 | val args = bundleOf("id" to item.id)
42 | findNavController().navigate(R.id.action_ListFragment_to_InfoFragment, args,
43 | null, extras)
44 | }.apply { addLoadStateListener { binding.loadState = it.refresh } }
45 |
46 | binding.characterAdapter = charactersAdapter
47 |
48 | lifecycleScope.launch {
49 | viewModel.flow.collectLatest { pagingData ->
50 | charactersAdapter.submitData(pagingData)
51 | }
52 | }
53 | }
54 |
55 | override fun onDestroyView() {
56 | super.onDestroyView()
57 | _binding = null
58 | }
59 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/rosariopfernandes/minibrothereye/ui/list/ListViewModel.kt:
--------------------------------------------------------------------------------
1 | package io.github.rosariopfernandes.minibrothereye.ui.list
2 |
3 | import androidx.hilt.lifecycle.ViewModelInject
4 | import androidx.lifecycle.ViewModel
5 | import androidx.lifecycle.viewModelScope
6 | import androidx.paging.Pager
7 | import androidx.paging.PagingConfig
8 | import androidx.paging.cachedIn
9 | import io.github.rosariopfernandes.minibrothereye.data.CharacterPagingSource
10 | import io.github.rosariopfernandes.minibrothereye.repository.CharacterRepository
11 |
12 | class ListViewModel @ViewModelInject constructor(
13 | private val repository: CharacterRepository
14 | ) : ViewModel() {
15 | val flow = Pager(PagingConfig(pageSize = 4, prefetchDistance = 4)) {
16 | CharacterPagingSource(repository)
17 | }.flow.cachedIn(viewModelScope)
18 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/rosariopfernandes/minibrothereye/util/Constants.kt:
--------------------------------------------------------------------------------
1 | package io.github.rosariopfernandes.minibrothereye.util
2 |
3 | const val PREF_DARK_THEME = "io.github.rosariopfernandes.minibrothereye.dark_theme"
4 | const val API_BASE_URL = "https://rosariopfernandes.github.io/dc-villains-api/"
5 |
--------------------------------------------------------------------------------
/app/src/main/java/io/github/rosariopfernandes/minibrothereye/util/DataBinding.kt:
--------------------------------------------------------------------------------
1 | package io.github.rosariopfernandes.minibrothereye.util
2 |
3 | import android.text.TextUtils
4 | import android.view.View
5 | import android.widget.ImageView
6 | import android.widget.ProgressBar
7 | import android.widget.TextView
8 | import androidx.core.view.isGone
9 | import androidx.core.view.isVisible
10 | import androidx.databinding.BindingAdapter
11 | import androidx.paging.LoadState
12 | import androidx.recyclerview.widget.RecyclerView
13 | import coil.api.load
14 | import io.github.rosariopfernandes.minibrothereye.R
15 | import io.github.rosariopfernandes.minibrothereye.model.Biography
16 | import io.github.rosariopfernandes.minibrothereye.model.Connections
17 | import io.github.rosariopfernandes.minibrothereye.model.PowerStats
18 | import io.github.rosariopfernandes.minibrothereye.model.Work
19 | import io.github.rosariopfernandes.minibrothereye.ui.characterinfo.PowerStatAdapter
20 |
21 | @BindingAdapter("adapter")
22 | fun bindRecyclerViewAdapter(view: RecyclerView, adapter: RecyclerView.Adapter<*>) {
23 | view.adapter = adapter
24 | }
25 |
26 | @BindingAdapter("powerStats")
27 | fun bindRecyclerViewAdapter(view: RecyclerView, powerStats: PowerStats) {
28 | view.adapter = PowerStatAdapter(powerStats)
29 | }
30 |
31 | @BindingAdapter("visibility")
32 | fun bindRecyclerViewVisibility(recyclerView: RecyclerView, state: LoadState) {
33 | when (state) {
34 | is LoadState.Loading -> recyclerView.isGone = true
35 | is LoadState.Error -> recyclerView.isGone = true
36 | else -> recyclerView.isVisible = true
37 | }
38 | }
39 |
40 | @BindingAdapter("visibility")
41 | fun bindProgressBarVisibility(progressBar: ProgressBar, state: LoadState) {
42 | when (state) {
43 | is LoadState.Loading -> progressBar.isVisible = true
44 | is LoadState.Error -> progressBar.isGone = true
45 | else -> progressBar.isGone = true
46 | }
47 | }
48 |
49 | @BindingAdapter("visibility")
50 | fun bindErrorTextViewVisibility(tvError: TextView, state: LoadState) {
51 | when (state) {
52 | is LoadState.Loading -> tvError.isGone = true
53 | is LoadState.Error -> {
54 | tvError.setText(R.string.error_cant_load_data)
55 | state.error.printStackTrace()
56 | tvError.isVisible = true
57 | }
58 | else -> tvError.isGone = true
59 | }
60 | }
61 |
62 | @BindingAdapter("isVisibile")
63 | fun bindVisibility(view: View, isVisible: Boolean) {
64 | view.visibility = if (isVisible) View.VISIBLE else View.GONE
65 | }
66 |
67 | @BindingAdapter("imageSrc")
68 | fun bindImageView(imageView: ImageView, url: String) {
69 | imageView.load(url) {
70 | crossfade(true)
71 | placeholder(R.drawable.no_portrait)
72 | error(R.drawable.no_portrait)
73 | }
74 | }
75 |
76 | @BindingAdapter("biography", "work", "connections")
77 | fun bindCharacterBiography(
78 | textView: TextView,
79 | biography: Biography,
80 | work: Work,
81 | connections: Connections
82 | ) {
83 | val context = textView.context
84 | var bioText = ""
85 |
86 | if (biography.fullName != "") {
87 | bioText += context.getString(R.string.label_bio_name, biography.fullName)
88 | }
89 | bioText += if (biography.alignment == "bad") {
90 | context.getString(R.string.label_villain)
91 | } else {
92 | context.getString(R.string.label_antihero)
93 | }
94 | if (biography.placeOfBirth != "-") {
95 | bioText += context.getString(R.string.label_bio_place_of_birth, biography.placeOfBirth)
96 | }
97 | if (biography.alterEgos != "No alter egos found.") {
98 | bioText += context.getString(R.string.label_bio_alteregos, biography.alterEgos)
99 | }
100 | bioText += "."
101 | if (biography.firstAppearance != "-") {
102 | bioText += context.getString(R.string.label_bio_firstAppearance, biography.firstAppearance)
103 | }
104 | if (work.occupation != "-") {
105 | bioText += context.getString(R.string.label_bio_occupation, work.occupation)
106 | }
107 | if (work.base != "-") {
108 | bioText += context.getString(R.string.label_bio_work_base, work.base)
109 | }
110 | if (connections.groupAffiliation != "-") {
111 | bioText += context.getString(R.string.label_bio_affiliation, connections.groupAffiliation)
112 | }
113 | if (connections.relatives != "-") {
114 | bioText += context.getString(R.string.label_bio_relatives, connections.relatives)
115 | }
116 | if (biography.aliases.isNotEmpty() && biography.aliases[0] != "-") {
117 | bioText += context.getString(R.string.label_bio_aliases, TextUtils.join(", ", biography.aliases))
118 | }
119 | textView.text = bioText
120 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/rosariopfernandes/minibrothereye/util/StringListConverters.kt:
--------------------------------------------------------------------------------
1 | package io.github.rosariopfernandes.minibrothereye.util
2 |
3 | import androidx.room.TypeConverter
4 | import com.google.gson.Gson
5 | import com.google.gson.reflect.TypeToken
6 |
7 | object StringListConverters {
8 | @TypeConverter
9 | @JvmStatic
10 | fun fromString(json: String): List {
11 | return Gson().fromJson(json, object : TypeToken>() {}.type)
12 | }
13 |
14 | @TypeConverter
15 | @JvmStatic
16 | fun fromStringList(list: List) = Gson().toJson(list)
17 | }
--------------------------------------------------------------------------------
/app/src/main/res/anim/grid_layout_animation.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/app/src/main/res/anim/item_from_bottom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
10 |
11 |
16 |
17 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_brightness_high_white_24dp.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_brightness_medium_white_24dp.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/no_portrait.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thatfiredev/MiniBrotherEye/aacd9f759a11c653ad6cb50051c3bac4085d062e/app/src/main/res/drawable/no_portrait.jpg
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
14 |
15 |
20 |
21 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/content_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
19 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/fragment_character_info.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
10 |
11 |
12 |
16 |
17 |
20 |
21 |
30 |
31 |
38 |
39 |
42 |
43 |
52 |
53 |
69 |
70 |
85 |
86 |
87 |
88 |
96 |
97 |
100 |
101 |
108 |
109 |
116 |
117 |
124 |
125 |
135 |
136 |
146 |
147 |
157 |
158 |
171 |
172 |
185 |
186 |
199 |
200 |
201 |
202 |
203 |
212 |
213 |
216 |
217 |
232 |
233 |
247 |
248 |
249 |
250 |
251 |
252 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/fragment_list.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
10 |
13 |
14 |
15 |
19 |
20 |
27 |
28 |
39 |
40 |
51 |
52 |
53 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/item_character.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
10 |
11 |
12 |
19 |
20 |
24 |
25 |
32 |
33 |
43 |
44 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/item_powerstat.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
23 |
24 |
32 |
--------------------------------------------------------------------------------
/app/src/main/res/menu/menu_main.xml:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thatfiredev/MiniBrotherEye/aacd9f759a11c653ad6cb50051c3bac4085d062e/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thatfiredev/MiniBrotherEye/aacd9f759a11c653ad6cb50051c3bac4085d062e/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thatfiredev/MiniBrotherEye/aacd9f759a11c653ad6cb50051c3bac4085d062e/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thatfiredev/MiniBrotherEye/aacd9f759a11c653ad6cb50051c3bac4085d062e/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thatfiredev/MiniBrotherEye/aacd9f759a11c653ad6cb50051c3bac4085d062e/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thatfiredev/MiniBrotherEye/aacd9f759a11c653ad6cb50051c3bac4085d062e/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thatfiredev/MiniBrotherEye/aacd9f759a11c653ad6cb50051c3bac4085d062e/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thatfiredev/MiniBrotherEye/aacd9f759a11c653ad6cb50051c3bac4085d062e/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thatfiredev/MiniBrotherEye/aacd9f759a11c653ad6cb50051c3bac4085d062e/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thatfiredev/MiniBrotherEye/aacd9f759a11c653ad6cb50051c3bac4085d062e/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/navigation/nav_graph.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
13 |
14 |
17 |
18 |
23 |
24 |
27 |
28 |
--------------------------------------------------------------------------------
/app/src/main/res/values-night/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #000000
4 |
5 | #FF8A80
6 | #B388FF
7 | #8C9EFF
8 | #B9F6CA
9 | #FFFF8D
10 | #FFE57F
11 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #6200EE
4 | #3700B3
5 | #03DAC5
6 |
7 | #D50000
8 | #6200EA
9 | #304FFE
10 | #00C853
11 | #FFD600
12 | #FFAB00
13 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 | 16dp
3 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Mini BrotherEye
3 | Light Theme
4 | Dark Theme
5 |
6 | Characters List
7 | Second Fragment
8 | Next
9 | Previous
10 |
11 | Hello second fragment. Arg: %1$s
12 | There was an error loading the data. Are you connected to the internet?
13 |
14 | Gender
15 | Height
16 | Weight
17 |
18 | Biography
19 |
20 | Intelligence
21 | Durability
22 | Strength
23 | Speed
24 | Power
25 | Combat
26 |
27 | Villain
28 | Antihero
29 |
30 | %s is a
31 | " born in %s"
32 | , also known as %s
33 | " They first appeared in %s"
34 | " Known for working as %s"
35 | , usually at %s.
36 | " \nAffiliations: %s."
37 | " Related to: %s."
38 | " Some of their aliases include %s."
39 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
9 |
10 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/app/src/test/java/io/github/rosariopfernandes/minibrothereye/data/CharacterDaoTest.kt:
--------------------------------------------------------------------------------
1 | package io.github.rosariopfernandes.minibrothereye.data
2 |
3 | import androidx.room.Room
4 | import androidx.test.ext.junit.runners.AndroidJUnit4
5 | import androidx.test.platform.app.InstrumentationRegistry
6 | import io.github.rosariopfernandes.minibrothereye.model.Character
7 | import kotlinx.coroutines.runBlocking
8 | import org.junit.After
9 | import org.junit.Assert.assertTrue
10 | import org.junit.Before
11 | import org.junit.Test
12 | import org.junit.runner.RunWith
13 | import org.robolectric.annotation.Config
14 |
15 | @RunWith(AndroidJUnit4::class)
16 | @Config(manifest = Config.NONE, sdk = [28])
17 | class CharacterDaoTest {
18 |
19 | private val context = InstrumentationRegistry.getInstrumentation().context
20 | private lateinit var database: AppDatabase
21 |
22 | private val character1 = Character(id = 1)
23 | private val character2 = Character(id = 2)
24 | private val characters = listOf(character1, character2)
25 |
26 | @Before
27 | fun createDatabase() {
28 | database = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)
29 | .build()
30 | }
31 |
32 | @After
33 | fun closeDatabase() {
34 | database.close()
35 | }
36 |
37 | @Test
38 | fun insertCharacter_savesData() = runBlocking {
39 | database.characterDao().insertCharacter(character1)
40 | val savedCharacters = database.characterDao().get4Characters(0)
41 | assertTrue(savedCharacters.isNotEmpty())
42 | }
43 |
44 | @Test
45 | fun insertCharacters_savesData() = runBlocking {
46 | var savedCharacters = database.characterDao().get4Characters(0)
47 | assertTrue(savedCharacters.isEmpty())
48 | database.characterDao().insertAll(characters)
49 | savedCharacters = database.characterDao().get4Characters(0)
50 | assertTrue(savedCharacters.isNotEmpty())
51 | }
52 |
53 | @Test
54 | fun getAll_retrievesData() = runBlocking {
55 | for (character in characters) {
56 | database.characterDao().insertCharacter(character)
57 | }
58 | val retrievedCharacters = database.characterDao().get4Characters(0)
59 | assertTrue(retrievedCharacters == characters)
60 | }
61 |
62 | @Test
63 | fun getInfo_retrievesData() = runBlocking {
64 | database.characterDao().insertCharacter(character1)
65 | val retrievedCharacter = database.characterDao().getInfo(1)
66 | assertTrue(retrievedCharacter == character1)
67 | }
68 | }
--------------------------------------------------------------------------------
/app/src/test/java/io/github/rosariopfernandes/minibrothereye/network/CharacterServiceTest.kt:
--------------------------------------------------------------------------------
1 | package io.github.rosariopfernandes.minibrothereye.network
2 |
3 | import io.github.rosariopfernandes.minibrothereye.util.API_BASE_URL
4 | import kotlinx.coroutines.runBlocking
5 | import okhttp3.mockwebserver.MockResponse
6 | import okhttp3.mockwebserver.MockWebServer
7 | import org.junit.Assert.assertFalse
8 | import org.junit.Assert.assertTrue
9 | import org.junit.Test
10 | import retrofit2.Retrofit
11 | import retrofit2.converter.gson.GsonConverterFactory
12 |
13 | class CharacterServiceTest {
14 |
15 | private lateinit var mockWebServer: MockWebServer
16 | private val mockResponseCharacterInfo = """
17 | {
18 | "id": 20,
19 | "name": "Amazo",
20 | "slug": "20-amazo",
21 | "powerstats": {
22 | "intelligence": 63,
23 | "strength": 100,
24 | "speed": 83,
25 | "durability": 100,
26 | "power": 100,
27 | "combat": 100
28 | },
29 | "appearance": {
30 | "gender": "Male",
31 | "race": "Android",
32 | "height": [
33 | "8'5",
34 | "257 cm"
35 | ],
36 | "weight": [
37 | "385 lb",
38 | "173 kg"
39 | ],
40 | "eyeColor": "Red",
41 | "hairColor": "-"
42 | },
43 | "biography": {
44 | "fullName": "",
45 | "alterEgos": "No alter egos found.",
46 | "aliases": [
47 | "Professor Ivos Amazing Android",
48 | "Timazo",
49 | "Humazo",
50 | "Hourmazo"
51 | ],
52 | "placeOfBirth": "-",
53 | "firstAppearance": "Brave and the Bold #30 (July, 1960)",
54 | "publisher": "DC Comics",
55 | "alignment": "bad"
56 | },
57 | "work": {
58 | "occupation": "-",
59 | "base": "-"
60 | },
61 | "connections": {
62 | "groupAffiliation": "Formerly the Secret Society of Super Villains",
63 | "relatives": "Professor Ivo (creator), Kid Amazo (cyborg offspring)"
64 | },
65 | "images": {
66 | "xs": "https://cdn.rawgit.com/akabab/superhero-api/0.2.0/api/images/xs/20-amazo.jpg",
67 | "sm": "https://cdn.rawgit.com/akabab/superhero-api/0.2.0/api/images/sm/20-amazo.jpg",
68 | "md": "https://cdn.rawgit.com/akabab/superhero-api/0.2.0/api/images/md/20-amazo.jpg",
69 | "lg": "https://cdn.rawgit.com/akabab/superhero-api/0.2.0/api/images/lg/20-amazo.jpg"
70 | }
71 | }
72 | """.trimIndent()
73 |
74 | private val mockResponseAllCharacters = "[$mockResponseCharacterInfo]"
75 |
76 |
77 | /**
78 | * Helper method to get a CharacterService instance
79 | */
80 | private fun getCharacterService(): CharacterService {
81 | val baseUrl = mockWebServer.url(API_BASE_URL)
82 | val retrofit = Retrofit.Builder()
83 | .baseUrl(baseUrl)
84 | .addConverterFactory(GsonConverterFactory.create())
85 | .build()
86 | return retrofit.create(CharacterService::class.java)
87 | }
88 |
89 | @Test
90 | fun getCharactersList_canBeParsed() = runBlocking {
91 | mockWebServer = MockWebServer()
92 | mockWebServer.enqueue(MockResponse().setBody(mockResponseAllCharacters))
93 | mockWebServer.start()
94 |
95 | val service = getCharacterService()
96 |
97 | val characters = service.getCharacterList()
98 | assertFalse(characters.isEmpty())
99 | assertTrue(characters[0].id == 20)
100 | assertTrue(characters[0].name == "Amazo")
101 |
102 | mockWebServer.shutdown()
103 | }
104 |
105 | @Test
106 | fun getCharactersInfo_canBeParsed() = runBlocking {
107 | mockWebServer = MockWebServer()
108 | mockWebServer.enqueue(MockResponse().setBody(mockResponseCharacterInfo))
109 | mockWebServer.start()
110 |
111 | val service = getCharacterService()
112 |
113 | val characterInfo = service.getCharacterInfo(20)
114 | assertTrue(characterInfo.id == 20)
115 |
116 | mockWebServer.shutdown()
117 | }
118 | }
--------------------------------------------------------------------------------
/app/src/test/java/io/github/rosariopfernandes/minibrothereye/repository/CharacterRepositoryTest.kt:
--------------------------------------------------------------------------------
1 | package io.github.rosariopfernandes.minibrothereye.repository
2 |
3 | import io.github.rosariopfernandes.minibrothereye.data.CharacterDao
4 | import io.github.rosariopfernandes.minibrothereye.model.Character
5 | import io.github.rosariopfernandes.minibrothereye.network.CharacterService
6 | import kotlinx.coroutines.runBlocking
7 | import org.junit.Assert.assertEquals
8 | import org.junit.Assert.assertTrue
9 | import org.junit.Before
10 | import org.junit.Test
11 | import org.mockito.Mockito.`when`
12 | import org.mockito.Mockito.mock
13 |
14 | class CharacterRepositoryTest {
15 | private val character1 = Character(id = 1) // cached
16 | private val character2 = Character(id = 2) // cached
17 | private val character3 = Character(id = 3) // network
18 | private val character4 = Character(id = 4) // network
19 | private val character5 = Character(id = 5) // cached
20 | private val character6 = Character(id = 6) // cached
21 | private val cachedCharacters = listOf(character1, character2, character5, character6)
22 | private val networkCharacters = listOf(character3, character4)
23 |
24 | private lateinit var mockCharacterDao: CharacterDao
25 | private lateinit var mockCharacterService: CharacterService
26 |
27 | private lateinit var repository: CharacterRepository
28 |
29 | @Before
30 | fun createRepository(): Unit = runBlocking {
31 | mockCharacterService = mock(CharacterService::class.java)
32 | mockCharacterDao = mock(CharacterDao::class.java)
33 | `when`(mockCharacterService.getCharacterList()).thenReturn(networkCharacters)
34 | `when`(mockCharacterService.getCharacterInfo(3)).thenReturn(character3)
35 | `when`(mockCharacterService.getCharacterInfo(4)).thenReturn(character4)
36 |
37 | `when`(mockCharacterDao.get4Characters(0)).thenReturn(cachedCharacters)
38 | `when`(mockCharacterDao.getInfo(1)).thenReturn(character1)
39 | `when`(mockCharacterDao.getInfo(2)).thenReturn(character2)
40 | repository = CharacterRepositoryImpl(mockCharacterDao, mockCharacterService)
41 | }
42 |
43 | @Test
44 | fun fetchCharacterPage_returnsExactly4Characters() = runBlocking {
45 | val actualCharacters = repository.fetchCharacterPage(0)
46 | assertEquals(cachedCharacters, actualCharacters)
47 | assertTrue(actualCharacters.size == 4)
48 | }
49 |
50 | @Test
51 | fun fetchCharacterInfo_returnsCharacterWithSpecificIdFromCache() = runBlocking {
52 | var actualCharacter = repository.fetchCharacterInfo(1)
53 | assertEquals(character1, actualCharacter)
54 | assertEquals(character1.id, actualCharacter.id)
55 |
56 | actualCharacter = repository.fetchCharacterInfo(2)
57 | assertEquals(character2, actualCharacter)
58 | assertEquals(character2.id, actualCharacter.id)
59 | }
60 |
61 | @Test
62 | fun fetchCharacterInfo_returnsCharacterWithSpecificIdFromNetwork() = runBlocking {
63 | var actualCharacter = repository.fetchCharacterInfo(3)
64 | assertEquals(character3, actualCharacter)
65 | assertEquals(character3.id, actualCharacter.id)
66 |
67 | actualCharacter = repository.fetchCharacterInfo(4)
68 | assertEquals(character4, actualCharacter)
69 | assertEquals(character4.id, actualCharacter.id)
70 | }
71 |
72 | }
--------------------------------------------------------------------------------
/app/src/test/java/io/github/rosariopfernandes/minibrothereye/ui/characterinfo/CharacterInfoViewModelTest.kt:
--------------------------------------------------------------------------------
1 | package io.github.rosariopfernandes.minibrothereye.ui.characterinfo
2 |
3 | import androidx.arch.core.executor.testing.InstantTaskExecutorRule
4 | import androidx.lifecycle.Observer
5 | import androidx.test.ext.junit.runners.AndroidJUnit4
6 | import io.github.rosariopfernandes.minibrothereye.model.Character
7 | import io.github.rosariopfernandes.minibrothereye.util.FakeCharacterRepository
8 | import org.junit.Assert.assertEquals
9 | import org.junit.Assert.assertTrue
10 | import org.junit.Rule
11 | import org.junit.Test
12 | import org.junit.runner.RunWith
13 | import java.lang.NullPointerException
14 | import kotlin.Exception
15 |
16 | @RunWith(AndroidJUnit4::class)
17 | class CharacterInfoViewModelTest {
18 |
19 | @get:Rule
20 | var instantExecutorRule = InstantTaskExecutorRule()
21 |
22 | @Test
23 | fun fetchCharacterInfo_canGenerateException() {
24 | val fakeRepository = FakeCharacterRepository(forceException = true)
25 | val viewModel = CharacterInfoViewModel(fakeRepository)
26 |
27 | val observer = Observer {}
28 | try {
29 | viewModel.exception.observeForever(observer)
30 | viewModel.fetchCharacterInfo(1)
31 | val exception = viewModel.exception.value!!
32 | assertTrue(exception is NullPointerException)
33 | } finally {
34 | viewModel.exception.removeObserver(observer)
35 | }
36 | }
37 |
38 | @Test
39 | fun fetchCharacterInfo_canGetCharacterInfo() {
40 | val fakeRepository = FakeCharacterRepository()
41 | val viewModel = CharacterInfoViewModel(fakeRepository)
42 |
43 | val observer = Observer {}
44 | try {
45 | viewModel.characterInfo.observeForever(observer)
46 | viewModel.fetchCharacterInfo(1)
47 | val character = viewModel.characterInfo.value!!
48 | assertEquals(1, character.id)
49 | } finally {
50 | viewModel.characterInfo.removeObserver(observer)
51 | }
52 | }
53 | }
--------------------------------------------------------------------------------
/app/src/test/java/io/github/rosariopfernandes/minibrothereye/util/FakeCharacterRepository.kt:
--------------------------------------------------------------------------------
1 | package io.github.rosariopfernandes.minibrothereye.util
2 |
3 | import io.github.rosariopfernandes.minibrothereye.model.Character
4 | import io.github.rosariopfernandes.minibrothereye.repository.CharacterRepository
5 |
6 | class FakeCharacterRepository(
7 | private val forceException: Boolean = false
8 | ) : CharacterRepository {
9 | override suspend fun fetchCharacterPage(offset: Int): List {
10 | if (forceException) {
11 | throw NullPointerException()
12 | }
13 | return listOf(Character(id = 1), Character(id = 2), Character(id = 3), Character(id = 4))
14 | }
15 |
16 | override suspend fun fetchCharacterInfo(characterId: Int): Character {
17 | if (forceException) {
18 | throw NullPointerException()
19 | }
20 | return Character(id = characterId)
21 | }
22 | }
--------------------------------------------------------------------------------
/art/screenshots.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thatfiredev/MiniBrotherEye/aacd9f759a11c653ad6cb50051c3bac4085d062e/art/screenshots.png
--------------------------------------------------------------------------------
/build.gradle.kts:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 | buildscript {
3 | extra.apply {
4 | set("kotlin_version", "1.3.72")
5 | set("hilt_version", "2.28-alpha")
6 | }
7 | repositories {
8 | google()
9 | jcenter()
10 | }
11 | dependencies {
12 | val kotlinVersion = project.extra["kotlin_version"] as String
13 | val hiltVersion = project.extra["hilt_version"] as String
14 | classpath("com.android.tools.build:gradle:4.0.0")
15 | classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion")
16 | classpath("com.google.dagger:hilt-android-gradle-plugin:$hiltVersion")
17 | // NOTE: Do not place your application dependencies here; they belong
18 | // in the individual module build.gradle files
19 | }
20 | }
21 |
22 | allprojects {
23 | repositories {
24 | google()
25 | jcenter()
26 | }
27 | }
28 |
29 | tasks.register("clean", Delete::class) {
30 | delete(rootProject.buildDir)
31 | }
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app"s APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Automatically convert third-party libraries to use AndroidX
19 | android.enableJetifier=true
20 | # Kotlin code style for this project: "official" or "obsolete":
21 | kotlin.code.style=official
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thatfiredev/MiniBrotherEye/aacd9f759a11c653ad6cb50051c3bac4085d062e/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Thu Jun 25 16:41:06 CAT 2020
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/settings.gradle.kts:
--------------------------------------------------------------------------------
1 | include(":app")
2 | rootProject.name = "Mini Brother Eye"
--------------------------------------------------------------------------------