Issue
What I need to happen is as follow:
- Start loop
- I need to have the intent go to the class to get a result
- Result will be one of two things, were both are needed to exit the while loop.
- Exit loop
Code:
while ( plate == "0" || location == "0"){
Toast.makeText(this, "Starting scan", Toast.LENGTH_SHORT).show()
val intent = Intent(this, LocationScan::class.java)
// 0 is request code
startActivityForResult(intent, 0)}
What happens currently is the screen flashes and Toast
keeps displaying. Intent does not load. Disabling loop takes me to intent and displays result.
plate
and location
is changed by the result of LocationScan
. Result is received by :
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
// Get the result from intent
val result = intent.getStringExtra("result")
if (result!![0] in 'a'..'z' || result!![0] in 'A'..'Z'){
location = result
println("$result is an location.")}
else{
plate = result
println("$result is a plate.")}
} } }
Compile Sdk : 33 Gradle Version : 7.4 Android Gradle Version :7.3.1 Java : 1.8
Solution
Closing/suspending the current Activity to open a new one requires the main thread to do a bunch of work, including calling onPause
in this Activity. So calling startActivityForResult
won't create the new Activity immediately, it'll schedule the transition for the future.
And it can't carry that transition out while you're blocking the main thread spinning on a loop. Even if it did immediately interrupt execution, it wouldn't return to the same point in your code (you're even relying on it calling onActivityResult
instead). Activities and Fragments just don't work like that.
What you probably want to do instead, is have a function that checks your conditions. If they're not met, call startActivityForResult
and let execution continue. Then in onActivityResult
, handle the result and then call the checking function again. If the conditions still aren't met, it'll start the Activity again, onActivityResult
will be called again, the checking function will run again...
So this way, you're creating a cycle that runs through the Activity system and its callbacks - it's still looping behaviour, but it's not an actual execution loop, if you see what I mean. You're effectively putting the task back on the queue until everything's taken care of, instead of blocking the thread.
Answered By - cactustictacs
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.