-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathKotlin_Android_Mobile_Reference.kt
More file actions
3685 lines (3149 loc) · 122 KB
/
Kotlin_Android_Mobile_Reference.kt
File metadata and controls
3685 lines (3149 loc) · 122 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// KOTLIN ANDROID MOBILE DEVELOPMENT - Comprehensive Reference - by Richard Rembert
// Kotlin is the preferred language for Android development, offering modern syntax,
// null safety, coroutines, and seamless Java interoperability for building robust mobile apps
// ═══════════════════════════════════════════════════════════════════════════════
// 1. SETUP AND PROJECT STRUCTURE
// ═══════════════════════════════════════════════════════════════════════════════
/*
KOTLIN ANDROID DEVELOPMENT SETUP:
1. Android Studio Installation:
- Download from: https://developer.android.com/studio
- Include Android SDK, emulator, and build tools
- Enable Kotlin plugin (included by default)
2. Project Creation:
- Choose "Empty Activity" or "Basic Activity"
- Select Kotlin as language
- Choose minimum SDK (API 24+ recommended)
- Enable Jetpack Compose for modern UI
3. Essential Dependencies (app/build.gradle.kts):
android {
compileSdk 34
defaultConfig {
applicationId "com.example.myapp"
minSdk 24
targetSdk 34
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables.useSupportLibrary = true
}
buildFeatures {
compose = true
viewBinding = true
dataBinding = true
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = "17"
}
composeOptions {
kotlinCompilerExtensionVersion = "1.5.4"
}
}
dependencies {
// Core Android
implementation("androidx.core:core-ktx:1.12.0")
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.7.0")
implementation("androidx.activity:activity-compose:1.8.1")
// Jetpack Compose
implementation(platform("androidx.compose:compose-bom:2023.10.01"))
implementation("androidx.compose.ui:ui")
implementation("androidx.compose.ui:ui-graphics")
implementation("androidx.compose.ui:ui-tooling-preview")
implementation("androidx.compose.material3:material3")
// Navigation
implementation("androidx.navigation:navigation-compose:2.7.5")
implementation("androidx.navigation:navigation-fragment-ktx:2.7.5")
implementation("androidx.navigation:navigation-ui-ktx:2.7.5")
// Architecture Components
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.7.0")
implementation("androidx.lifecycle:lifecycle-livedata-ktx:2.7.0")
implementation("androidx.room:room-runtime:2.6.0")
implementation("androidx.room:room-ktx:2.6.0")
kapt("androidx.room:room-compiler:2.6.0")
// Dependency Injection
implementation("com.google.dagger:hilt-android:2.48")
implementation("androidx.hilt:hilt-navigation-compose:1.1.0")
kapt("com.google.dagger:hilt-compiler:2.48")
// Networking
implementation("com.squareup.retrofit2:retrofit:2.9.0")
implementation("com.squareup.retrofit2:converter-gson:2.9.0")
implementation("com.squareup.okhttp3:logging-interceptor:4.12.0")
// Image Loading
implementation("io.coil-kt:coil-compose:2.5.0")
// Coroutines
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3")
// Testing
testImplementation("junit:junit:4.13.2")
testImplementation("org.mockito:mockito-core:5.6.0")
testImplementation("androidx.arch.core:core-testing:2.2.0")
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.3")
androidTestImplementation("androidx.test.ext:junit:1.1.5")
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
androidTestImplementation("androidx.compose.ui:ui-test-junit4")
debugImplementation("androidx.compose.ui:ui-tooling")
debugImplementation("androidx.compose.ui:ui-test-manifest")
}
4. Project Structure:
app/
├── src/
│ ├── main/
│ │ ├── java/com/example/myapp/
│ │ │ ├── data/
│ │ │ │ ├── local/
│ │ │ │ ├── remote/
│ │ │ │ ├── repository/
│ │ │ │ └── model/
│ │ │ ├── domain/
│ │ │ │ ├── repository/
│ │ │ │ ├── usecase/
│ │ │ │ └── model/
│ │ │ ├── presentation/
│ │ │ │ ├── ui/
│ │ │ │ ├── viewmodel/
│ │ │ │ └── navigation/
│ │ │ ├── di/
│ │ │ └── utils/
│ │ ├── res/
│ │ └── AndroidManifest.xml
│ ├── test/
│ └── androidTest/
└── build.gradle.kts
*/
package com.example.myapp
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
// ═══════════════════════════════════════════════════════════════════════════════
// 2. APPLICATION CLASS AND DEPENDENCY INJECTION
// ═══════════════════════════════════════════════════════════════════════════════
@HiltAndroidApp
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
// Initialize any required libraries
initializeLibraries()
// Setup crash reporting (Firebase Crashlytics, Bugsnag, etc.)
setupCrashReporting()
// Setup analytics
setupAnalytics()
}
private fun initializeLibraries() {
// Initialize third-party libraries if needed
// Example: Timber for logging, LeakCanary for memory leak detection
}
private fun setupCrashReporting() {
// Setup crash reporting service
}
private fun setupAnalytics() {
// Setup analytics service
}
}
// ═══════════════════════════════════════════════════════════════════════════════
// 3. DEPENDENCY INJECTION WITH HILT
// ═══════════════════════════════════════════════════════════════════════════════
package com.example.myapp.di
import android.content.Context
import androidx.room.Room
import com.example.myapp.data.local.AppDatabase
import com.example.myapp.data.local.UserDao
import com.example.myapp.data.remote.ApiService
import com.example.myapp.data.repository.UserRepositoryImpl
import com.example.myapp.domain.repository.UserRepository
import com.example.myapp.utils.Constants
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object DatabaseModule {
@Provides
@Singleton
fun provideAppDatabase(@ApplicationContext context: Context): AppDatabase {
return Room.databaseBuilder(
context,
AppDatabase::class.java,
"app_database"
)
.fallbackToDestructiveMigration()
.build()
}
@Provides
fun provideUserDao(database: AppDatabase): UserDao = database.userDao()
}
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
@Provides
@Singleton
fun provideGson(): Gson {
return GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
.create()
}
@Provides
@Singleton
fun provideOkHttpClient(): OkHttpClient {
val loggingInterceptor = HttpLoggingInterceptor().apply {
level = if (BuildConfig.DEBUG) {
HttpLoggingInterceptor.Level.BODY
} else {
HttpLoggingInterceptor.Level.NONE
}
}
return OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
.addInterceptor { chain ->
val request = chain.request().newBuilder()
.addHeader("Content-Type", "application/json")
.addHeader("Accept", "application/json")
.build()
chain.proceed(request)
}
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.build()
}
@Provides
@Singleton
fun provideRetrofit(gson: Gson, okHttpClient: OkHttpClient): Retrofit {
return Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create(gson))
.build()
}
@Provides
@Singleton
fun provideApiService(retrofit: Retrofit): ApiService = retrofit.create(ApiService::class.java)
}
@Module
@InstallIn(SingletonComponent::class)
object RepositoryModule {
@Provides
@Singleton
fun provideUserRepository(
apiService: ApiService,
userDao: UserDao
): UserRepository {
return UserRepositoryImpl(apiService, userDao)
}
}
// ═══════════════════════════════════════════════════════════════════════════════
// 4. DATA MODELS AND ENTITIES
// ═══════════════════════════════════════════════════════════════════════════════
package com.example.myapp.data.model
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.google.gson.annotations.SerializedName
import java.util.Date
// Domain Models (Clean Architecture)
package com.example.myapp.domain.model
data class User(
val id: String,
val email: String,
val username: String,
val firstName: String,
val lastName: String,
val avatarUrl: String? = null,
val isActive: Boolean = true,
val createdAt: Date,
val updatedAt: Date
) {
val fullName: String
get() = "$firstName $lastName"
val initials: String
get() = "${firstName.firstOrNull()?.uppercase()}${lastName.firstOrNull()?.uppercase()}"
}
data class Post(
val id: String,
val title: String,
val content: String,
val excerpt: String,
val imageUrl: String? = null,
val authorId: String,
val author: User? = null,
val categoryId: String,
val category: Category? = null,
val tags: List<String> = emptyList(),
val isPublished: Boolean = false,
val viewCount: Int = 0,
val likeCount: Int = 0,
val commentCount: Int = 0,
val publishedAt: Date? = null,
val createdAt: Date,
val updatedAt: Date
) {
val readingTimeMinutes: Int
get() = (content.split(" ").size / 200).coerceAtLeast(1)
val isPublic: Boolean
get() = isPublished && publishedAt != null
}
data class Category(
val id: String,
val name: String,
val slug: String,
val description: String,
val color: String,
val postCount: Int = 0
)
data class Comment(
val id: String,
val content: String,
val postId: String,
val authorId: String,
val author: User? = null,
val parentId: String? = null,
val replies: List<Comment> = emptyList(),
val createdAt: Date,
val updatedAt: Date
)
// Data Transfer Objects (DTOs)
package com.example.myapp.data.model
data class UserDto(
@SerializedName("id") val id: String,
@SerializedName("email") val email: String,
@SerializedName("username") val username: String,
@SerializedName("first_name") val firstName: String,
@SerializedName("last_name") val lastName: String,
@SerializedName("avatar_url") val avatarUrl: String?,
@SerializedName("is_active") val isActive: Boolean,
@SerializedName("created_at") val createdAt: String,
@SerializedName("updated_at") val updatedAt: String
)
data class PostDto(
@SerializedName("id") val id: String,
@SerializedName("title") val title: String,
@SerializedName("content") val content: String,
@SerializedName("excerpt") val excerpt: String,
@SerializedName("image_url") val imageUrl: String?,
@SerializedName("author_id") val authorId: String,
@SerializedName("author") val author: UserDto?,
@SerializedName("category_id") val categoryId: String,
@SerializedName("category") val category: CategoryDto?,
@SerializedName("tags") val tags: List<String>,
@SerializedName("is_published") val isPublished: Boolean,
@SerializedName("view_count") val viewCount: Int,
@SerializedName("like_count") val likeCount: Int,
@SerializedName("comment_count") val commentCount: Int,
@SerializedName("published_at") val publishedAt: String?,
@SerializedName("created_at") val createdAt: String,
@SerializedName("updated_at") val updatedAt: String
)
data class CategoryDto(
@SerializedName("id") val id: String,
@SerializedName("name") val name: String,
@SerializedName("slug") val slug: String,
@SerializedName("description") val description: String,
@SerializedName("color") val color: String,
@SerializedName("post_count") val postCount: Int
)
// Room Database Entities
package com.example.myapp.data.local.entity
@Entity(tableName = "users")
data class UserEntity(
@PrimaryKey val id: String,
val email: String,
val username: String,
val firstName: String,
val lastName: String,
val avatarUrl: String?,
val isActive: Boolean,
val createdAt: Long,
val updatedAt: Long
)
@Entity(tableName = "posts")
data class PostEntity(
@PrimaryKey val id: String,
val title: String,
val content: String,
val excerpt: String,
val imageUrl: String?,
val authorId: String,
val categoryId: String,
val tags: String, // JSON string
val isPublished: Boolean,
val viewCount: Int,
val likeCount: Int,
val commentCount: Int,
val publishedAt: Long?,
val createdAt: Long,
val updatedAt: Long
)
@Entity(tableName = "categories")
data class CategoryEntity(
@PrimaryKey val id: String,
val name: String,
val slug: String,
val description: String,
val color: String,
val postCount: Int
)
// ═══════════════════════════════════════════════════════════════════════════════
// 5. DATA MAPPERS
// ═══════════════════════════════════════════════════════════════════════════════
package com.example.myapp.data.mapper
import com.example.myapp.data.local.entity.UserEntity
import com.example.myapp.data.model.UserDto
import com.example.myapp.domain.model.User
import java.text.SimpleDateFormat
import java.util.*
object UserMapper {
private val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault())
fun dtoToDomain(dto: UserDto): User {
return User(
id = dto.id,
email = dto.email,
username = dto.username,
firstName = dto.firstName,
lastName = dto.lastName,
avatarUrl = dto.avatarUrl,
isActive = dto.isActive,
createdAt = dateFormat.parse(dto.createdAt) ?: Date(),
updatedAt = dateFormat.parse(dto.updatedAt) ?: Date()
)
}
fun dtoToEntity(dto: UserDto): UserEntity {
return UserEntity(
id = dto.id,
email = dto.email,
username = dto.username,
firstName = dto.firstName,
lastName = dto.lastName,
avatarUrl = dto.avatarUrl,
isActive = dto.isActive,
createdAt = dateFormat.parse(dto.createdAt)?.time ?: 0L,
updatedAt = dateFormat.parse(dto.updatedAt)?.time ?: 0L
)
}
fun entityToDomain(entity: UserEntity): User {
return User(
id = entity.id,
email = entity.email,
username = entity.username,
firstName = entity.firstName,
lastName = entity.lastName,
avatarUrl = entity.avatarUrl,
isActive = entity.isActive,
createdAt = Date(entity.createdAt),
updatedAt = Date(entity.updatedAt)
)
}
fun domainToEntity(user: User): UserEntity {
return UserEntity(
id = user.id,
email = user.email,
username = user.username,
firstName = user.firstName,
lastName = user.lastName,
avatarUrl = user.avatarUrl,
isActive = user.isActive,
createdAt = user.createdAt.time,
updatedAt = user.updatedAt.time
)
}
}
object PostMapper {
private val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault())
private val gson = Gson()
fun dtoToDomain(dto: PostDto): Post {
return Post(
id = dto.id,
title = dto.title,
content = dto.content,
excerpt = dto.excerpt,
imageUrl = dto.imageUrl,
authorId = dto.authorId,
author = dto.author?.let { UserMapper.dtoToDomain(it) },
categoryId = dto.categoryId,
category = dto.category?.let { CategoryMapper.dtoToDomain(it) },
tags = dto.tags,
isPublished = dto.isPublished,
viewCount = dto.viewCount,
likeCount = dto.likeCount,
commentCount = dto.commentCount,
publishedAt = dto.publishedAt?.let { dateFormat.parse(it) },
createdAt = dateFormat.parse(dto.createdAt) ?: Date(),
updatedAt = dateFormat.parse(dto.updatedAt) ?: Date()
)
}
fun entityToDomain(entity: PostEntity): Post {
val tags = try {
gson.fromJson(entity.tags, Array<String>::class.java).toList()
} catch (e: Exception) {
emptyList<String>()
}
return Post(
id = entity.id,
title = entity.title,
content = entity.content,
excerpt = entity.excerpt,
imageUrl = entity.imageUrl,
authorId = entity.authorId,
categoryId = entity.categoryId,
tags = tags,
isPublished = entity.isPublished,
viewCount = entity.viewCount,
likeCount = entity.likeCount,
commentCount = entity.commentCount,
publishedAt = entity.publishedAt?.let { Date(it) },
createdAt = Date(entity.createdAt),
updatedAt = Date(entity.updatedAt)
)
}
fun domainToEntity(post: Post): PostEntity {
return PostEntity(
id = post.id,
title = post.title,
content = post.content,
excerpt = post.excerpt,
imageUrl = post.imageUrl,
authorId = post.authorId,
categoryId = post.categoryId,
tags = gson.toJson(post.tags),
isPublished = post.isPublished,
viewCount = post.viewCount,
likeCount = post.likeCount,
commentCount = post.commentCount,
publishedAt = post.publishedAt?.time,
createdAt = post.createdAt.time,
updatedAt = post.updatedAt.time
)
}
}
object CategoryMapper {
fun dtoToDomain(dto: CategoryDto): Category {
return Category(
id = dto.id,
name = dto.name,
slug = dto.slug,
description = dto.description,
color = dto.color,
postCount = dto.postCount
)
}
fun entityToDomain(entity: CategoryEntity): Category {
return Category(
id = entity.id,
name = entity.name,
slug = entity.slug,
description = entity.description,
color = entity.color,
postCount = entity.postCount
)
}
fun domainToEntity(category: Category): CategoryEntity {
return CategoryEntity(
id = category.id,
name = category.name,
slug = category.slug,
description = category.description,
color = category.color,
postCount = category.postCount
)
}
}
// ═══════════════════════════════════════════════════════════════════════════════
// 6. DATABASE LAYER (ROOM)
// ═══════════════════════════════════════════════════════════════════════════════
package com.example.myapp.data.local
import androidx.room.*
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.example.myapp.data.local.entity.CategoryEntity
import com.example.myapp.data.local.entity.PostEntity
import com.example.myapp.data.local.entity.UserEntity
import kotlinx.coroutines.flow.Flow
@Dao
interface UserDao {
@Query("SELECT * FROM users WHERE id = :id")
suspend fun getUserById(id: String): UserEntity?
@Query("SELECT * FROM users WHERE email = :email")
suspend fun getUserByEmail(email: String): UserEntity?
@Query("SELECT * FROM users ORDER BY firstName, lastName")
fun getAllUsers(): Flow<List<UserEntity>>
@Query("SELECT * FROM users WHERE firstName LIKE '%' || :query || '%' OR lastName LIKE '%' || :query || '%' OR username LIKE '%' || :query || '%'")
fun searchUsers(query: String): Flow<List<UserEntity>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertUser(user: UserEntity)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertUsers(users: List<UserEntity>)
@Update
suspend fun updateUser(user: UserEntity)
@Delete
suspend fun deleteUser(user: UserEntity)
@Query("DELETE FROM users WHERE id = :id")
suspend fun deleteUserById(id: String)
@Query("DELETE FROM users")
suspend fun deleteAllUsers()
}
@Dao
interface PostDao {
@Query("SELECT * FROM posts WHERE id = :id")
suspend fun getPostById(id: String): PostEntity?
@Query("SELECT * FROM posts WHERE isPublished = 1 ORDER BY publishedAt DESC")
fun getPublishedPosts(): Flow<List<PostEntity>>
@Query("SELECT * FROM posts WHERE authorId = :authorId ORDER BY createdAt DESC")
fun getPostsByAuthor(authorId: String): Flow<List<PostEntity>>
@Query("SELECT * FROM posts WHERE categoryId = :categoryId AND isPublished = 1 ORDER BY publishedAt DESC")
fun getPostsByCategory(categoryId: String): Flow<List<PostEntity>>
@Query("SELECT * FROM posts WHERE title LIKE '%' || :query || '%' OR content LIKE '%' || :query || '%'")
fun searchPosts(query: String): Flow<List<PostEntity>>
@Query("SELECT * FROM posts ORDER BY viewCount DESC LIMIT :limit")
fun getPopularPosts(limit: Int): Flow<List<PostEntity>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertPost(post: PostEntity)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertPosts(posts: List<PostEntity>)
@Update
suspend fun updatePost(post: PostEntity)
@Delete
suspend fun deletePost(post: PostEntity)
@Query("DELETE FROM posts WHERE id = :id")
suspend fun deletePostById(id: String)
@Query("UPDATE posts SET viewCount = viewCount + 1 WHERE id = :id")
suspend fun incrementViewCount(id: String)
@Query("UPDATE posts SET likeCount = :likeCount WHERE id = :id")
suspend fun updateLikeCount(id: String, likeCount: Int)
}
@Dao
interface CategoryDao {
@Query("SELECT * FROM categories WHERE id = :id")
suspend fun getCategoryById(id: String): CategoryEntity?
@Query("SELECT * FROM categories ORDER BY name")
fun getAllCategories(): Flow<List<CategoryEntity>>
@Query("SELECT * FROM categories WHERE name LIKE '%' || :query || '%'")
fun searchCategories(query: String): Flow<List<CategoryEntity>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertCategory(category: CategoryEntity)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertCategories(categories: List<CategoryEntity>)
@Update
suspend fun updateCategory(category: CategoryEntity)
@Delete
suspend fun deleteCategory(category: CategoryEntity)
}
@Database(
entities = [UserEntity::class, PostEntity::class, CategoryEntity::class],
version = 1,
exportSchema = false
)
@TypeConverters(Converters::class)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
abstract fun postDao(): PostDao
abstract fun categoryDao(): CategoryDao
companion object {
const val DATABASE_NAME = "app_database"
// Example migration (when needed)
val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE users ADD COLUMN bio TEXT")
}
}
}
}
class Converters {
@TypeConverter
fun fromStringList(value: List<String>): String {
return Gson().toJson(value)
}
@TypeConverter
fun toStringList(value: String): List<String> {
return try {
Gson().fromJson(value, Array<String>::class.java).toList()
} catch (e: Exception) {
emptyList()
}
}
}
// ═══════════════════════════════════════════════════════════════════════════════
// 7. NETWORK LAYER (RETROFIT)
// ═══════════════════════════════════════════════════════════════════════════════
package com.example.myapp.data.remote
import com.example.myapp.data.model.*
import retrofit2.Response
import retrofit2.http.*
interface ApiService {
// Authentication
@POST("auth/login")
suspend fun login(@Body request: LoginRequest): Response<AuthResponse>
@POST("auth/register")
suspend fun register(@Body request: RegisterRequest): Response<AuthResponse>
@POST("auth/refresh")
suspend fun refreshToken(@Body request: RefreshTokenRequest): Response<AuthResponse>
@POST("auth/logout")
suspend fun logout(): Response<Unit>
// Users
@GET("users/{id}")
suspend fun getUserById(@Path("id") id: String): Response<ApiResponse<UserDto>>
@GET("users")
suspend fun getUsers(
@Query("page") page: Int = 1,
@Query("limit") limit: Int = 20,
@Query("search") search: String? = null
): Response<PaginatedResponse<UserDto>>
@PUT("users/{id}")
suspend fun updateUser(
@Path("id") id: String,
@Body request: UpdateUserRequest
): Response<ApiResponse<UserDto>>
@DELETE("users/{id}")
suspend fun deleteUser(@Path("id") id: String): Response<Unit>
// Posts
@GET("posts")
suspend fun getPosts(
@Query("page") page: Int = 1,
@Query("limit") limit: Int = 20,
@Query("category") category: String? = null,
@Query("author") author: String? = null,
@Query("search") search: String? = null,
@Query("published") published: Boolean? = null
): Response<PaginatedResponse<PostDto>>
@GET("posts/{id}")
suspend fun getPostById(@Path("id") id: String): Response<ApiResponse<PostDto>>
@POST("posts")
suspend fun createPost(@Body request: CreatePostRequest): Response<ApiResponse<PostDto>>
@PUT("posts/{id}")
suspend fun updatePost(
@Path("id") id: String,
@Body request: UpdatePostRequest
): Response<ApiResponse<PostDto>>
@DELETE("posts/{id}")
suspend fun deletePost(@Path("id") id: String): Response<Unit>
@POST("posts/{id}/like")
suspend fun likePost(@Path("id") id: String): Response<Unit>
@DELETE("posts/{id}/like")
suspend fun unlikePost(@Path("id") id: String): Response<Unit>
@POST("posts/{id}/view")
suspend fun incrementPostView(@Path("id") id: String): Response<Unit>
// Categories
@GET("categories")
suspend fun getCategories(): Response<ApiResponse<List<CategoryDto>>>
@GET("categories/{id}")
suspend fun getCategoryById(@Path("id") id: String): Response<ApiResponse<CategoryDto>>
// Comments
@GET("posts/{postId}/comments")
suspend fun getComments(
@Path("postId") postId: String,
@Query("page") page: Int = 1,
@Query("limit") limit: Int = 20
): Response<PaginatedResponse<CommentDto>>
@POST("posts/{postId}/comments")
suspend fun createComment(
@Path("postId") postId: String,
@Body request: CreateCommentRequest
): Response<ApiResponse<CommentDto>>
@PUT("comments/{id}")
suspend fun updateComment(
@Path("id") id: String,
@Body request: UpdateCommentRequest
): Response<ApiResponse<CommentDto>>
@DELETE("comments/{id}")
suspend fun deleteComment(@Path("id") id: String): Response<Unit>
}
// API Request/Response Models
data class LoginRequest(
val email: String,
val password: String
)
data class RegisterRequest(
val email: String,
val username: String,
val firstName: String,
val lastName: String,
val password: String
)
data class RefreshTokenRequest(
val refreshToken: String
)
data class AuthResponse(
val accessToken: String,
val refreshToken: String,
val expiresIn: Long,
val user: UserDto
)
data class UpdateUserRequest(
val firstName: String?,
val lastName: String?,
val username: String?,
val bio: String?
)
data class CreatePostRequest(
val title: String,
val content: String,
val excerpt: String?,
val categoryId: String,
val tags: List<String>,
val isPublished: Boolean = false
)
data class UpdatePostRequest(
val title: String?,
val content: String?,
val excerpt: String?,
val categoryId: String?,
val tags: List<String>?,
val isPublished: Boolean?
)
data class CreateCommentRequest(
val content: String,
val parentId: String? = null
)
data class UpdateCommentRequest(
val content: String
)
// Generic API Response Wrappers
data class ApiResponse<T>(
val success: Boolean,
val data: T?,
val message: String?,
val errors: List<String>?
)
data class PaginatedResponse<T>(
val success: Boolean,
val data: List<T>,
val pagination: PaginationInfo,
val message: String?,
val errors: List<String>?
)
data class PaginationInfo(
val currentPage: Int,
val totalPages: Int,
val totalItems: Int,
val itemsPerPage: Int,
val hasNext: Boolean,
val hasPrevious: Boolean
)
// ═══════════════════════════════════════════════════════════════════════════════
// 8. REPOSITORY LAYER