Ramakrishnan logoRamakrishnan.Mobile Developer
WorkSkillsAboutContact
Available for new projects

Blog & Articles

Thoughts on Mobile Product Design

I share insights on UX strategy, Flutter architecture, performance optimization, and lessons from shipping apps at scale.

Apr 26, 2026

How I Use Hive Database in My Flutter App (LifeOS)

Offline-first local storage with a clean repository pattern How I built a fast, privacy-first personal admin app without a backend. The Problem Most apps today rely heavily on APIs and cloud storage. But in real-world scenarios: Users expect instant loading Internet is not always reliable Privacy concerns are increasing While building my app LifeOS — Smart Life Admin , I wanted: ⚡ Fast performance 🔒 Complete privacy 📶 Offline-first experience That’s when I chose Hive as my local database. This article shows exactly how I use Hive in my app, from initialization to CRUD operations, with a structure you can copy into your own Flutter project. Why Hive? Hive is a key-value database written in pure Dart. For my use case, it gave me: very simple setup strong performance for local data clean integration with Flutter no SQL boilerplate If your app stores structured local data and does not need complex SQL joins, Hive is a great choice. What is LifeOS? LifeOS is a smart personal admin app to manage: Bills Subscriptions Tasks Reminders My App Structure I keep database logic in a repository so UI and state management stay clean. main.dart initializes Hive AppRepository opens boxes and performs read/write/delete each model (BillItem, SubscriptionItem, TaskItem) handles serialization with toMap() / fromMap() This keeps storage concerns in one place. 1) Initialize Hive at Startup In main(), initialize Flutter bindings first, then Hive, then create the repository. Future<void> main() async { WidgetsFlutterBinding.ensureInitialized(); await Hive.initFlutter(); final repository = await AppRepository.create(); runApp( ProviderScope( overrides: [appRepositoryProvider.overrideWithValue(repository)], child: const LifeOsApp(), ), ); } Why this matters: boxes must be available before UI starts reading data. 2) Open Boxes per Feature Domain Inside my repository: class AppRepository { AppRepository._(this._billsBox, this._subscriptionsBox, this._tasksBox); final Box<dynamic> _billsBox; final Box<dynamic> _subscriptionsBox; final Box<dynamic> _tasksBox; static Future<AppRepository> create() async { final bills = await Hive.openBox<dynamic>('bills_box'); final subscriptions = await Hive.openBox<dynamic>('subscriptions_box'); final tasks = await Hive.openBox<dynamic>('tasks_box'); return AppRepository._(bills, subscriptions, tasks); } } I split boxes by feature. This keeps data organized and easier to maintain. 3) Serialize Models with toMap() and fromMap() I store maps in Hive, then rebuild typed models when reading. Map<String, dynamic> toMap() => { 'id': id, 'name': name, 'amount': amount, 'dueDate': dueDate.toIso8601String(), }; factory BillItem.fromMap(Map<dynamic, dynamic> map) { return BillItem( id: map['id'] as String, name: map['name'] as String, amount: (map['amount'] as num).toDouble(), dueDate: DateTime.parse(map['dueDate'] as String), ); } Tip: store DateTime as ISO strings (toIso8601String) and parse on read. 4) CRUD Operations in Repository Save Future<void> saveBill(BillItem bill) => _billsBox.put(bill.id, bill.toMap()); Load List<BillItem> loadBills() { return _billsBox.values .map((v) => BillItem.fromMap(Map<dynamic, dynamic>.from(v as Map))) .toList(); } Delete Future<void> deleteBill(String id) => _billsBox.delete(id); I use the model id as the Hive key. That makes updates and deletes straightforward. 5) Connect Repository to App State I inject repository once at app startup and use it from my state layer (Riverpod). This avoids direct Hive calls from widgets. Result: cleaner UI code testable data layer easier future migration if storage changes Common Mistakes I Avoided Not calling WidgetsFlutterBinding.ensureInitialized() before async setup. Opening boxes in many places instead of one repository factory. Mixing raw maps and model objects in UI code. Forgetting type-safe conversion when reading from dynamic. When to Use Hive (and When Not To) Use Hive when: you need local/offline app data data model is moderate and structured you want quick setup When NOT to Use Hive Avoid Hive if: You need complex relational queries You have very large datasets You need multi-user sync Final Thoughts Hive helped me ship a fast, offline-friendly Flutter app with minimal complexity. The biggest win was combining Hive with a repository layer and model serialization. If you are building a task, finance, habit, or utility app, this pattern is a practical starting point. Part 2 (Coming Soon) In Part 2, I’ll cover: Using TypeAdapters for stronger type safety and better performance Handling schema changes with simple migration strategies Writing unit tests for a Hive-powered repository in Flutter Avoiding common production issues (box versioning, fallback values, data cleanup)

Read on Medium →
Apr 24, 2026

Built AppScope: A Simple Android App to Help Users Understand and Free Up Storage

Built AppScope — an Android app that helps users understand what’s taking up storage on their phone. Smartphones are powerful, but one problem never really goes away: storage fills up fast. Photos, videos, social apps, games, cached files, downloads, and app data all grow quietly in the background until the device starts slowing down or showing the dreaded “Storage Almost Full” warning. That problem inspired me to build AppScope — a clean Android utility that helps users quickly understand which apps are using the most storage, how that storage is divided between App / Data / Cache, and what actions they can take to reclaim space. Why I Built It Most users don’t want technical details. They want simple answers to questions like: Which apps are taking the most space? How much of that is actual app size vs data vs cache? Can I free some space without uninstalling the app? Which apps should I look at first? AppScope was designed to answer those questions with a simple, visual, and fast experience. What AppScope Does At its core, AppScope is a storage analyzer for installed apps on Android. It helps users: View installed apps ranked by storage usage Understand the storage breakdown of each app See total device storage usage in a visual way Spot heavy apps and large cache usage Take quick actions such as: Open app Clear cache through system settings Uninstall app The goal is simple: make storage management less confusing and more useful for everyday users. Key Features Installed Apps by Storage Usage The home screen focuses on the most important information first. Users can: Search for apps instantly Sort apps by size or name Filter by app type View the top storage-consuming apps with progress indicators See a modern storage overview card with a visual chart Instead of overwhelming the screen with raw numbers, the design highlights the largest storage consumers first. 2. Storage Overview A dedicated storage card shows: Total storage used Total device capacity A visual chart representing storage usage A quick breakdown of space categories This gives users immediate context before they dive into app-level details. 3. Storage Breakdown AppScope separates usage into three categories: App (APK) — installed application files Data — user data, settings, files, and accounts Cache — temporary files that may be cleared This is especially important because many users assume an app’s size is only the app binary, when in reality data and cache can grow much larger over time. 4. App Details Screen Each app has a dedicated details view showing: App icon and package information Total storage used Donut chart for storage distribution Breakdown rows for App / Data / Cache Version Install date Last updated date Smart insights Quick action buttons The details screen was designed to feel like a focused dashboard rather than a system settings page. 5. Smart Insights To make the app more useful, AppScope includes lightweight rules such as: Flagging heavy apps Detecting large cache usage Suggesting space-saving actions For example: “This app is using high storage” “Clear cache to free space” These insights are intentionally simple so users can act quickly without needing technical knowledge. Design Goals From the beginning, I wanted AppScope to feel: Fast Minimal Readable Useful without internet Friendly for non-technical users The UI uses large numbers, clear labels, and color-coded categories: Blue for App Green for Data Orange for Cache The latest iteration also uses a darker visual theme with bold cards and chart-based summaries to make the information feel more modern and easier to scan. Technical Approach AppScope is built as a native Android app using a modern Android stack. Architecture The app follows a simple layered structure: Repository layer for system and package data access ViewModels for state management Compose UI for the interface Coroutines + Flows for async and reactive updates This keeps the UI clean and makes it easier to progressively load app information without blocking the main thread. Data Sources To get app storage information, the app uses Android system APIs such as: PackageManager for installed apps and metadata StorageStatsManager for app/data/cache bytes DataStore for settings persistence This allows AppScope to provide real installed-app information rather than static sample content. Progressive Loading One important part of the experience is that the app does not wait for everything before showing the UI. Instead, it progressively loads app storage information and updates the screen as data becomes available. This makes the app feel much faster, especially on devices with many installed apps. Privacy and Offline-First Thinking One of the strongest ideas behind AppScope is that it should work offline and avoid unnecessary data collection. This is not a cloud service. It is a device utility. That means: App data stays on the device No internet is required for core features The app focuses on system-level information already available on Android That makes it more trustworthy for users who simply want to manage storage without sharing personal information. Challenges While Building It Like many Android utilities, this project had a few practical challenges: Permission Handling Some storage-related details require access through Android system permission flows. That means the app has to guide users clearly and handle denied states gracefully. Large App Lists On devices with a lot of apps installed, performance matters. The app had to support: Smooth scrolling Progressive updates Efficient UI state handling Low memory overhead Making Technical Data Understandable The raw information from Android APIs is useful, but not always friendly. A big part of the work is converting system-level data into something that feels obvious and actionable for real users. AppScope is trying to do something simpler: show the right information, visually, and make the next action obvious. That means the app focuses on clarity over complexity. There are still a lot of improvements that can make AppScope even better, including: Better usage insights for recently used and unused apps More detailed storage analytics Improved app comparison views Better onboarding for permissions Polished charts and animations Export or summary reporting More customization in filtering and sorting The foundation is now in place, and the next step is refining the experience even further. Final Thoughts Building AppScope has been a reminder that even a small utility app can solve a very real problem. Storage management is something almost every smartphone user deals with, but the experience is often frustrating and unclear. AppScope is my attempt to make it simple, visual, and actually helpful. If you’ve ever wanted a cleaner way to understand what’s really taking up space on an Android device, that’s exactly what this app is built for. AppScope is not about doing everything. It’s about helping users see the problem clearly — and take action fast.

Read on Medium →
Apr 20, 2026

A Simple CLI Tool to Bootstrap Android Projects Instantly

How I packaged a Python automation tool as a standalone CLI that works like the android command The Problem Every Android developer knows the drill. New machine, new teammate, new CI environment — and you’re back to manually configuring the Android SDK, creating projects from scratch, and running android info to double-check everything is wired up correctly. I wanted a CLI tool that behaved like the android command itself: install once, run anywhere, no runtime dependencies. The catch? The logic was already written in Python. What the Agent Does The android-bootstrap-agent is a thin automation layer on top of the android CLI. It wraps four workflows into a single command: android-bootstrap-agent start # Full flow: check, create, verify android-bootstrap-agent create # Create project if missing android-bootstrap-agent verify # Verify existing project android-bootstrap-agent info # Check Android CLI environment Under the hood it: Checks that android — version succeeds Runs android info to validate SDK environment Optionally installs SDK packages via android sdk install Creates a project with android create <template> --name=... --output=... Verifies with android describe --project_dir=... The entire agent is a single Python file with zero third-party dependencies — only the standard library. The Architecture The agent is built around three clean pieces: AgentConfig — a dataclass holding all runtime configuration: @dataclass class AgentConfig: app_name: str = "My App" template: str = "empty-activity" output_dir: str = "./my-app" min_sdk: int = 24 create_on_start: bool = True overwrite_if_exists: bool = False timeout_sec: int = 120 required_sdk_packages: List[str] = None AndroidBootstrapAgent — the agent class with one method per workflow. Each method composes the lower-level _run_cmd, _ensure_android_cli, and _ensure_environment helpers. build_parser() — a standard argparse setup using subcommands and a shared common parent parser, so every command gets the same base flags: subparsers.add_parser("start", parents=[common]) subparsers.add_parser("create", parents=[common]) subparsers.add_parser("verify", parents=[common]) subparsers.add_parser("info", parents=[common]) This mirrors how the android CLI itself is structured. Making it Standalone — No Python Required The trick is PyInstaller. It bundles the Python interpreter and your script into a single native executable. pip install pyinstaller pyinstaller --onefile --name android-bootstrap-agent android_bootstrap_agent.py The result is a standalone binary in dist that runs on any machine of the same OS — no Python, no pip, no virtual environments. For a repeatable build I created a build.spec file instead of relying on CLI flags. This makes the build reproducible and easy to add to CI later. The Cross-Platform Reality This is the part most tutorials skip. PyInstaller does not cross-compile. The binary you build on Windows runs on Windows. The binary you build on Linux runs on Linux. The solution is a universal portable package: android-bootstrap-agent-universal/ ├── bin/ │ ├── windows-x64/ │ │ └── android-bootstrap-agent.exe │ ├── linux-x64/ │ │ └── android-bootstrap-agent │ └── macos-arm64/ │ └── android-bootstrap-agent ├── install.ps1 ← Windows installer ├── install.sh ← Linux/macOS installer └── README.md One zip file, one installer script per platform. The scripts handle PATH setup automatically. Windows (install.ps1): # Default: installs to user AppData, no admin needed .\install.ps1 # System-wide (requires admin shell) .\install.ps1 -Machine Linux/macOS (install.sh): chmod +x install.sh ./install.sh # Installs to ~/.local/bin and prints PATH guidance if needed After install, open a new terminal: android-bootstrap-agent --version # android-agent 0.1.0 Key Design Decisions No third-party libraries. The agent uses only argparse, subprocess, pathlib, and dataclasses. This keeps the binary small (~8 MB) and the build trivial. Fail fast with clear messages. Every subprocess failure raises an AgentError with a human-readable message. The __main__ block catches it and exits with code 1, making this CI-friendly. Idempotent by default. Running start twice on the same directory detects the existing project and skips creation — it won’t wipe your work unless you explicitly pass — overwrite-if-exists. Common parent parser. Using parents=[common] in argparse means all subcommands automatically inherit --app-name, --output-dir, --min-sdk, and the rest. No duplication, no drift. Running It # Check environment android-bootstrap-agent info # Full flow android-bootstrap-agent start --app-name "My App" --output-dir ./my-app # Create with a specific SDK package android-bootstrap-agent create \ --app-name "My App" \ --output-dir ./my-app \ --min-sdk 30 \ --sdk-package platforms/android-34 # Verify an existing project android-bootstrap-agent verify --output-dir ./my-app The Takeaway Packaging a Python CLI as a standalone binary is underrated. Your users get a clean install experience with no runtime dependencies, and you keep all the ergonomics of Python for writing the logic itself. PyInstaller handles the hard part. The extra step of building a universal package with platform-aware install scripts takes less than an hour and makes the tool genuinely portable — the same experience on every machine, every OS.

Read on Medium →
Mar 29, 2026

Building an Offline-First Flutter Finance App with Hive + Riverpod

A production-style architecture for local persistence, reactive streams with yield, and scalable provider design. Photo by micheile henderson on Unsplash If you’re building a finance app, users expect three things immediately: Fast UI Offline reliability Data consistency This post explains the architecture I used in a Flutter loan planner app to achieve all three, using Hive as local storage and Riverpod for state/data orchestration. The implementation references below come from: loan_provider.dart emi_reminder_provider.dart daily_tracker_provider.dart main.dart Why Hive + Riverpod for This Use Case For personal finance tools, an offline-first stack is usually the right default. Hive gives very fast local key-value access with simple APIs. Riverpod gives composable dependency management and reactive updates. Together, they create a clean separation: Persistence layer in providers UI layer reading AsyncValue Side effects in provider actions The practical result: fewer manual refresh bugs, less widget-level state complexity, and better maintainability. Architecture Overview The architecture can be described as a 4-stage pipeline: Initialize storage once at app startup. Expose boxes via simple providers. Read data reactively via StreamProvider + yield/yield*. Write data through FutureProvider.family command providers. Conceptually: UI (ref.watch) -> Riverpod Providers -> Hive Boxes -> Local device storage 1) Storage Bootstrapping and App Gatekeeping The startup provider in loan_provider.dart initializes Hive and opens all required boxes before the app proceeds. Key pattern final hiveProviderProvider = FutureProvider<void>((ref) async { await Hive.initFlutter(); if (!Hive.isAdapterRegistered(0)) { Hive.registerAdapter(LoanModelAdapter()); } await Hive.openBox<LoanModel>(loanBoxName); await Hive.openBox<dynamic>(emiReminderBoxName); await Hive.openBox<dynamic>(dailyExpenseBoxName); await Hive.openBox<dynamic>(expensePlannerBoxName); }); In main.dart, the UI watches this provider and gates app rendering with .when(...): Loading state while storage initializes Error state if initialization fails Main app only after storage is ready This avoids race conditions like calling Hive.box(...) before openBox(...). 2) Box Access as First-Class Dependencies Each box is exposed via a plain provider. Example from loan_provider.dart: final loanBoxProvider = Provider<Box<LoanModel>>((ref) { return Hive.box<LoanModel>(loanBoxName); }); This gives you: Dependency injection for storage access Easy mocking in tests Explicit ownership and clear data boundaries A similar approach is used in: emi_reminder_provider.dart daily_tracker_provider.dart 3) Reactive Reads with StreamProvider, yield, and yield* This is the most important pattern in the app. Example: loan list stream From loan_provider.dart: final loanListProvider = StreamProvider<List<LoanModel>>((ref) async* { final box = ref.watch(loanBoxProvider); yield box.values.toList(); yield* box.watch().map((_) => box.values.toList()); }); What exactly happens yield box.values.toList() emits an immediate snapshot. yield* box.watch().map(...) forwards all future box change events. UI subscribed with ref.watch(loanListProvider) gets live updates automatically. No manual event bus. No callback plumbing in widgets. No stale list refresh logic. Same pattern in reminders and daily tracker emi_reminder_provider.dart daily_tracker_provider.dart The daily tracker provider adds sorting before returning values, showing that stream transformations are a good place for deterministic ordering rules. 4) Write Commands with FutureProvider.family Writes are modeled as parameterized commands. Examples from loan_provider.dart final addLoanProvider = FutureProvider.family<void, LoanModel>((ref, loan) async { final box = ref.watch(loanBoxProvider); await box.put(loan.id, loan); }); final deleteLoanProvider = FutureProvider.family<void, String>((ref, loanId) async { final box = ref.watch(loanBoxProvider); await box.delete(loanId); }); Why this works well Arguments are explicit and typed. Side effects are centralized. UI remains declarative and thin. Business actions are reusable across screens. 5) Reminder Generation Algorithm (Data Layer) EMI reminder records are generated and saved in emi_reminder_provider.dart. Core behavior: Remove old reminders for the same loan. Compute elapsed months from start date to now. Generate only upcoming installments. Persist each reminder record with metadata. This is a good deterministic data-generation pattern because it is idempotent for a given loan snapshot. Practical note This implementation currently creates reminder data in Hive (in-app reminders). It does not yet schedule OS-level local notifications. To push phone notifications, add a notification service layer (flutter_local_notifications) and schedule/cancel jobs alongside these records. 6) UI Consumption Pattern: AsyncValue Done Right The UI flow follows Riverpod idioms: ref.watch(provider) handle loading, error, and data states explicitly render stable widgets from immutable snapshots This is visible in app boot flow in main.dart, and similarly on list-driven screens consuming stream providers. This pattern makes asynchronous state predictable and avoids hidden null/late initialization pitfalls. 7) Data Modeling Strategy The app uses two storage styles: Typed model box for loans (Box<LoanModel>) Dynamic map boxes for reminders/trackers (Box<dynamic> with map normalization) Typed boxes are great for domain entities with methods and strict schema. Dynamic boxes are useful for flexible payloads, quick evolution, and lightweight entries. When reading dynamic values, normalize with: .whereType<Map>() .map((e) => Map<String, dynamic>.from(e)) This guards against runtime shape drift and enforces a usable map contract downstream. 8) Performance and Correctness Considerations Performance Hive reads are local and fast. Stream updates are incremental event-driven. No repeated heavy computation in widget tree when provider transforms are used carefully. Correctness Initialization gate prevents uninitialized box usage. Provider-driven writes reduce duplicate mutation paths. Stream snapshots keep UI and DB state aligned. Important production caveat If you invoke command providers for side effects, prefer awaiting .future form where sequence matters. For example, if save must complete before navigation or next action, await the provider future. 9) Reusable Template: Hive + Riverpod + yield Use this baseline for any new module. import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:hive_flutter/hive_flutter.dart'; const myBoxName = 'my_box'; // 1) Box provider final myBoxProvider = Provider<Box<dynamic>>((ref) { return Hive.box<dynamic>(myBoxName); }); // 2) Reactive read provider final myListProvider = StreamProvider<List<Map<String, dynamic>>>((ref) async* { final box = ref.watch(myBoxProvider); // Initial snapshot yield box.values .whereType<Map>() .map((e) => Map<String, dynamic>.from(e)) .toList(); // Live updates yield* box.watch().map((_) { return box.values .whereType<Map>() .map((e) => Map<String, dynamic>.from(e)) .toList(); }); }); // 3) Save action final saveMyItemProvider = FutureProvider.family<void, Map<String, dynamic>>((ref, data) async { final box = ref.watch(myBoxProvider); final id = data['id'] as String; await box.put(id, data); }); // 4) Delete action final deleteMyItemProvider = FutureProvider.family<void, String>((ref, id) async { final box = ref.watch(myBoxProvider); await box.delete(id); }); 10) Suggested Evolution Path If you want to scale this architecture further: Add repository interfaces over providers for domain-level testing. Introduce dedicated notification service for OS-level EMI alerts. Add migration/version strategy for dynamic boxes. Add provider tests for stream ordering and mutation semantics. Add analytics around reminder generation success/failure. Final Thoughts The biggest win in this architecture is not Hive alone or Riverpod alone. It is the combination of local persistence + reactive streams + command-style writes. The yield + yield* pattern is the critical piece that makes offline data feel real-time in Flutter UI with almost no manual refresh logic. If you’re building finance, planner, or tracker apps, this pattern is a strong production baseline. https://play.google.com/store/apps/details?id=com.rk.nexloan

Read on Medium →
Dec 19, 2025

Building a Android News App Using Clean Architecture, MVVM, and RemoteMediator

Modern Android applications — especially news and feed-based apps — need to handle large datasets, pagination, offline caching, and frequent API updates. In this article, I’ll explain how I built a scalable News App using Clean Architecture , MVVM , Paging 3 RemoteMediator , and Kotlin Coroutines . Why Clean Architecture for a News App? News apps typically deal with: Continuous API calls Pagination Offline support Complex UI state handling Without a proper architecture, the codebase quickly becomes unmaintainable. To solve this, the app follows Clean Architecture, ensuring separation of concerns and long-term scalability. High-Level Architecture Diagram UI (Activity / Fragment / Compose) ↓ ViewModel (MVVM) ↓ Use Cases (Domain Layer) ↓ Repository ↓ RemoteMediator ↙ ↘ News API Room Database Each layer has a single responsibility , which makes testing, debugging, and feature expansion easier. Architecture Layers Explained 1. Presentation Layer (UI + ViewModel) Displays data Observes state No business logic 2. Domain Layer Contains use cases Holds business rules Independent of Android framework 3. Data Layer Fetches data from API Caches data locally Manages pagination and sync Pagination & Offline Support with RemoteMediator To efficiently handle paginated news feeds, the app uses Paging 3 with RemoteMediator . Why RemoteMediator? Syncs remote data with local cache Enables offline access Avoids unnecessary API calls RemoteMediator — Simplified Code Snippet @OptIn(ExperimentalPagingApi::class) class NewsRemoteMediator( private val api: NewsApi, private val database: NewsDatabase ) : RemoteMediator<Int, NewsEntity>() { override suspend fun load( loadType: LoadType, state: PagingState<Int, NewsEntity> ): MediatorResult { return try { val page = when (loadType) { LoadType.REFRESH -> 1 LoadType.APPEND -> getNextPage(state) LoadType.PREPEND -> return MediatorResult.Success(true) } val response = api.getNews(page) database.withTransaction { if (loadType == LoadType.REFRESH) { database.newsDao().clearAll() } database.newsDao().insertAll(response.articles) } MediatorResult.Success( endOfPaginationReached = response.articles.isEmpty() ) } catch (e: Exception) { MediatorResult.Error(e) } } } MVVM with Lifecycle Awareness The app follows MVVM to ensure: UI remains simple Logic stays in ViewModel No memory leaks ViewModel Example class NewsViewModel( private val repository: NewsRepository ) : ViewModel() { val newsFlow = repository.getNews() .cachedIn(viewModelScope) } ✔ Lifecycle-aware ✔ Automatic cancellation ✔ Smooth UI updates Background Processing with Kotlin Coroutines All heavy operations run in the background using Kotlin Coroutines : Network calls Database operations Pagination logic This ensures: No UI thread blocking Better performance Cleaner async code Handling UI States Using Sealed Classes Instead of multiple booleans, UI states are represented using sealed classes . UI State Example sealed class NewsUiState { object Loading : NewsUiState() data class Success(val data: List<Article>) : NewsUiState() object Empty : NewsUiState() data class Error(val message: String) : NewsUiState() } Usage in UI when (state) { is NewsUiState.Loading -> showLoading() is NewsUiState.Success -> showNews(state.data) is NewsUiState.Empty -> showEmpty() is NewsUiState.Error -> showError(state.message) } Clean Data Flow (End to End) User opens app ↓ ViewModel requests data ↓ Use case triggers repository ↓ RemoteMediator fetches API data ↓ Room stores data ↓ Paging serves cached data to UI This flow ensures performance, reliability, and offline access . Performance Benefits Smooth scrolling with Paging Reduced network usage Cached data for offline mode Automatic cancellation of background tasks Without a proper architecture, the codebase quickly becomes unmaintainable. To solve this, the app follows Clean Architecture , ensuring separation of concerns and long-term scalability.

Read on Medium →
Sep 26, 2024

Jetpack Compose Runtime Permissions

In this post, we’ll look at how to use Jetpack Compose to manage runtime permission requests in an Android app. For Android applications, Jetpack Compose offers a declarative method of managing runtime permissions. This method makes it easy for developers to ensure that their apps have the permissions they need to run correctly by streamlining the request and management of permissions. Add Permission in the Manifest: Every program requires an AndroidManifest.xml file, which should be located at the root of the project source set. The manifest file contains critical information about your app for the Android build tools, the Android operating system, and Google Play. <manifest ... > <uses-permission android:name="android.permission.CAMERA" /> <application ... </application> </manifest> Key Concepts: A composable function called PermissionRequest starts the permission request procedure. It accepts a permission code as an input and outputs a Boolean value indicating whether or not the request is approved. The permission status is represented by the enum class PermissionStatus, which has the following possible values: “Granted,” “Denied,” “Never Ask Again,” or “Unknown.” Launched Effect: A detachable effect that lets you apply side actions according to the situation at hand. It’s frequently used to handle authorization results and adjust the user interface (UI). @Composable fun CameraPermission() { val cameraPermissionState = rememberMultiplePermissionsState( permissions = listOf(Manifest.permission.CAMERA) ) when { cameraPermissionState.allPermissionsGranted -> { // Camera permission is granted } cameraPermissionState.shouldShowRationale -> { // Show explanation to the user } else -> { // Permission has been denied } } } } Multiple Permissions: You can request many permissions at once by providing a list of permission codes to PermissionRequest.launch. Rationale Permissions: If you request a potentially harmful permission, you must provide a reason to the user explaining why your app needs it. Revoke Permission: Users should revoke the permission at any time. The application will work on that scenario. In the main activity or any appropriate screen we call the cameraPermission() class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { CameraPermission() } } } Conclusion: Request permissions only when necessary, and provide clear explanations to the user. Handle permission results gracefully and provide alternative options if permission is denied. Consider using a library like Dexter or Permissions to simplify permission management.

Read on Medium →
May 27, 2024

Migrate Kapt to KSP

Hey folks, Throughout this series, we’ll discuss switching from KAPT to KSP. Kapt (the Kotlin Annotation Processing Tool) permits using Java annotation processors with Kotlin code, even if those processors don’t have specific support for Kotlin. This is done by generating Java stubs from your Kotlin files that the processors can read. This stub generation is an expensive operation and significantly impacts build speed. Moving from KAPT, Kotlin Symbol Processing (KSP) is an API that can use to develop lightweight compiler plugins. KSP will analyse the Kotlin code directly and run up to 2x faster. KSP is also designed to minimize build times. For some processors, such as Glide , KSP reduces full compilation times by up to 25% when compared to Kapt. How will the KSP be included in your project? In your project top-level build.gradle.kts include the KSP plugin plugins { id 'com.google.devtools.ksp' version '1.8.10-1.0.9' apply false } And next, enable the module-level build.gradle.kts file plugins { id 'com.google.devtools.ksp' } Replace the KAPT library with the KSP kapt 'androidx.room:room-compiler:2.5.0' //Remove ksp 'androidx.room:room-compiler:2.5.0' //Add After adding these dependencies sync your project Remove the KAPT plugin in your project: When you no longer require the KAPT requirements, delete the KAPT plugin. plugins { id 'org.jetbrains.kotlin.kapt' } //you should also remove the leftover kapt plugin in your project KSP2 is in Beta! KSP2 is a new implementation of the KSP API. It will be faster and easier to use than KSP 1.x. Please refer to the KSP2 introduction for more details. #Happy coding

Read on Medium →
Jan 27, 2022

Android LinearLayout

LinearLayout in android Ride the horse in the direction that it’s going. ~ Werner Erhard Hello, developer! Today we will discuss about Linear layout. If you start layout from vertical direction the flow will like vertical. And if you start layout from horizontal direction the flow will like horizontal. The following code will show a linear layout in vertical direction <LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android" android:layout_width=”match_parent” android:layout_height=”match_parent” android:orientation=”vertical”> <! — The other widgets like Images,Text and other layout will added in vertical → </LinearLayout> The following code will show a linear layout in vertical direction <LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android" android:layout_width=”match_parent” android:layout_height=”match_parent” android:orientation=“horizontal”> <! — The other widgets like Images,Text and other layout will added in horizontal → </LinearLayout> For more reference please visit — https://developer.android.com/reference/android/widget/LinearLayout?authuser=1 https://developer.android.com/guide/topics/ui/layout/linear Hope you find this helpful. Do not forgot to give some claps

Read on Medium →
Back to HomeBBaacckkttooHHoommee→