Is there a better way to write this? ```val launc...
# getting-started
s
Is there a better way to write this?
Copy code
val launchUri = try {
                if( isAvailable() ) {
                    Uri.parse( "..." )
                } else {
                    Uri.parse("..." )
                }
            } catch ( e : android.content.ActivityNotFoundException ) {
                if( isAvailable() ) {
                    Uri.parse( "..." )
                } else {
                    Uri.parse("..." )
                }
            }
t
pull out the uri to parse as a variable
v
is
"..."
different in each case? also what is throwing the exception?
t
Copy code
val uri = if(available) ... else ...
Uri.parse(uri)
s
@Vladyslav Sitalo Yes, "..." is different
Nevermind, the exception was from a left over
This is the refactored code. Logic is to find an activity that can handle the URL if not launch a browser. This works fine except too many blocks without ?: operator
Copy code
try {
                
                val launchUri = if( isAvailable() ) {
                    Uri.parse( "..." ) 
                } else {
                    Uri.parse("..." )
                }

                startActivity( Intent( Intent.ACTION_VIEW, launchUri ) )

            } catch ( e : android.content.ActivityNotFoundException ) {
                
                val launchUri = if( isAvailable() ) {
                    Uri.parse( "..." )
                } else {
                    Uri.parse("..." )
                }

                startActivity( Intent( Intent.ACTION_VIEW, launchUri ) )
            }
e
Maybe try it like this?
Copy code
val launchUri = if(isAvailable())
    Uri.parse("...")
else
    Uri.parse("...")
val intent = Intent(Intent.ACTION_VIEW, launchUri)

if(intent.resolveActivity(getPackageManager()) != null) {
    startActivity(intent)
else {
    //resolve new url and start activity
}
I don’t know exactly what is your logic because you don’t tell us if there’s 4 different uris or 2 or 3
i
@Sam, This and the prior are good posts for #codereview if you haven’t already seen that channel. 😊
s
Sure, good to know
👍 1