Skip to content

Fix: Prevent crash by moving Toast to main thread in UserRepo#253

Open
Tomeshwari-02 wants to merge 3 commits intoPSMRI:mainfrom
Tomeshwari-02:main
Open

Fix: Prevent crash by moving Toast to main thread in UserRepo#253
Tomeshwari-02 wants to merge 3 commits intoPSMRI:mainfrom
Tomeshwari-02:main

Conversation

@Tomeshwari-02
Copy link
Copy Markdown

@Tomeshwari-02 Tomeshwari-02 commented Apr 24, 2026

📋 Description

This PR fixes a potential crash caused by displaying a Toast from a background thread (Dispatchers.IO) in UserRepo.kt.

Previously, a Toast message ("Facility ID not found") was triggered inside an IO coroutine, which can lead to CalledFromWrongThreadException since UI operations must run on the main thread.

The fix ensures that the Toast is executed on Dispatchers.Main, making it safe and compliant with Android threading rules.


✅ Type of Change

  • 🐞 Bug fix (non-breaking change which resolves an issue)
  • New feature (non-breaking change which adds functionality)
  • 🔥 Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • 🛠 Refactor (change that is neither a fix nor a new feature)
  • ⚙️ Config change (configuration file or build script updates)
  • 📚 Documentation (updates to docs or readme)
  • 🧪 Tests (adding new or updating existing tests)
  • 🎨 UI/UX (changes that affect the user interface)
  • 🚀 Performance (improves performance)
  • 🧹 Chore (miscellaneous changes that don't modify src or test files)

ℹ️ Additional Information

Testing

Verified the login flow where the Toast is triggered
Confirmed that the Toast displays correctly without any crash
Ensured no impact on existing functionality

Notes

This is a minimal and safe fix
Improves app stability by ensuring UI operations run on the main thread
Aligns with Android best practices for coroutine usage

Summary by CodeRabbit

  • Bug Fixes
    • Fixed an issue where the "Facility ID not found" notification could fail to appear; it now reliably displays and pauses briefly before proceeding, preventing confusing silent failures.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 24, 2026

Warning

Rate limit exceeded

@Tomeshwari-02 has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 54 minutes and 32 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 54 minutes and 32 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 466fe843-d655-4f31-9eeb-8337efeb5005

📥 Commits

Reviewing files that changed from the base of the PR and between 4d02338 and 4f7f9e6.

📒 Files selected for processing (1)
  • app/src/main/java/org/piramalswasthya/cho/repositories/UserRepo.kt
📝 Walkthrough

Walkthrough

Refactored the missing-facilityID branch in getUserVanSpDetails to dispatch the "Facility ID not found" toast on the main thread via withContext(Dispatchers.Main), retaining the 3-second delay and the continue behavior.

Changes

Cohort / File(s) Summary
Main Thread Toast Dispatch
app/src/main/java/org/piramalswasthya/cho/repositories/UserRepo.kt
Moved the missing-facilityID toast display into withContext(Dispatchers.Main) so the toast is shown on the UI thread; preserved existing message, delay(3000), and continue flow. EOF newline corrected.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~3 minutes

Poem

🐰 I hopped a coroutine, light and fleet,
Found a missing ID, then tapped my feet,
"Facility not found!" I softly cried,
With withContext I hopped to the main-side,
The toast now blooms — hooray, UI's neat!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: moving Toast to main thread to prevent crashes in UserRepo, which aligns with the summary of using withContext(Dispatchers.Main) for the toast display.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
app/src/main/java/org/piramalswasthya/cho/repositories/UserRepo.kt (1)

229-237: ⚠️ Potential issue | 🟠 Major

Guard is ineffective — getInt("facilityID") on line 235 will still throw when the key is missing.

The !vanSp.has("facilityID") branch only shows a toast and sleeps; control then falls through to line 235 (vanSp.getInt("facilityID")), which will throw JSONException because the key does not exist. The net result is that after this PR the user sees the toast and the login flow still crashes/fails for the same input the toast was meant to warn about. Add a continue (to skip this entry) or return@withContext false inside the if block so the missing-facility case is actually handled.

🐛 Proposed fix
                     if (!vanSp.has("facilityID")) {
                         withContext(Dispatchers.Main) {
                             Toast.makeText(context, "Facility ID not found", Toast.LENGTH_LONG).show()
                         }
                         delay(3000)
+                        return@withContext false
                     }
                     val facilityId = vanSp.getInt("facilityID")

Use continue instead of return@withContext false if the intent is to skip this entry but still process subsequent vanSpDetailsArray elements.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/src/main/java/org/piramalswasthya/cho/repositories/UserRepo.kt` around
lines 229 - 237, The guard for missing "facilityID" is ineffective because after
showing the toast and delaying you still call vanSp.getInt("facilityID") which
will throw; inside the if (!vanSp.has("facilityID")) block (the block that shows
the Toast and delay) add a continue to skip this vanSp entry so you don't run
vanSp.getInt("facilityID") and assign user?.facilityID / user?.parkingPlaceId
for a missing key; this preserves processing of subsequent vanSpDetailsArray
elements.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@app/src/main/java/org/piramalswasthya/cho/repositories/UserRepo.kt`:
- Around line 229-237: The guard for missing "facilityID" is ineffective because
after showing the toast and delaying you still call vanSp.getInt("facilityID")
which will throw; inside the if (!vanSp.has("facilityID")) block (the block that
shows the Toast and delay) add a continue to skip this vanSp entry so you don't
run vanSp.getInt("facilityID") and assign user?.facilityID /
user?.parkingPlaceId for a missing key; this preserves processing of subsequent
vanSpDetailsArray elements.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 8b84949e-76c4-4f93-99a2-757b41d57e4e

📥 Commits

Reviewing files that changed from the base of the PR and between 4cfb776 and 5691e17.

📒 Files selected for processing (1)
  • app/src/main/java/org/piramalswasthya/cho/repositories/UserRepo.kt

@drtechie
Copy link
Copy Markdown
Member

@Tomeshwari-02 there are SonarCloud comments. Please check.

@drtechie
Copy link
Copy Markdown
Member

@sushant-bizbrolly please review

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@app/src/main/java/org/piramalswasthya/cho/repositories/UserRepo.kt`:
- Around line 223-229: The loop that iterates vanSpDetailsArray currently
continues past entries missing "facilityID", which can leave user (user.vanId,
user.servicePointId, user.servicePointName, user.facilityID,
user.parkingPlaceId) uninitialized while the function still returns true and
downstream callers like getLocDetailsBasedOnSpIDAndPsmID() dereference
user!!.vanId; fix by tracking whether at least one valid entry was processed
(e.g., processedFound flag) and return false if none were processed, move the
Toast + delay out of the per-item loop so you show a single message and do a
single delay (or break after the first toast) to avoid cumulative 3s×N blocking,
and keep using withContext(Dispatchers.Main) for the Toast instead of spawning
GlobalScope coroutines.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 3cf7824d-a8cd-4781-b014-214733a09e58

📥 Commits

Reviewing files that changed from the base of the PR and between 5691e17 and 4d02338.

📒 Files selected for processing (1)
  • app/src/main/java/org/piramalswasthya/cho/repositories/UserRepo.kt

Comment thread app/src/main/java/org/piramalswasthya/cho/repositories/UserRepo.kt
@sonarqubecloud
Copy link
Copy Markdown

@Tomeshwari-02
Copy link
Copy Markdown
Author

@Tomeshwari-02 there are SonarCloud comments. Please check.

Done 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants