diff --git a/app/src/main/java/com/github/libretube/ui/dialogs/CustomInstanceDialog.kt b/app/src/main/java/com/github/libretube/ui/dialogs/CustomInstanceDialog.kt index e2a5a41eb..9c4c41d8a 100644 --- a/app/src/main/java/com/github/libretube/ui/dialogs/CustomInstanceDialog.kt +++ b/app/src/main/java/com/github/libretube/ui/dialogs/CustomInstanceDialog.kt @@ -11,56 +11,37 @@ import com.github.libretube.db.DatabaseHolder.Companion.Database import com.github.libretube.db.obj.CustomInstance import com.github.libretube.extensions.query import com.google.android.material.dialog.MaterialAlertDialogBuilder -import java.net.URL +import okhttp3.HttpUrl.Companion.toHttpUrlOrNull class CustomInstanceDialog : DialogFragment() { - private lateinit var binding: DialogCustomInstanceBinding - override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { - binding = DialogCustomInstanceBinding.inflate(layoutInflater) + val binding = DialogCustomInstanceBinding.inflate(layoutInflater) binding.cancel.setOnClickListener { dismiss() } binding.addInstance.setOnClickListener { - val customInstance = CustomInstance( - name = binding.instanceName.text.toString(), - apiUrl = binding.instanceApiUrl.text.toString(), - frontendUrl = binding.instanceFrontendUrl.text.toString() - ) - - if ( - customInstance.name != "" && - customInstance.apiUrl != "" && - customInstance.frontendUrl != "" - ) { - try { - // check whether the URL is valid, otherwise catch - URL(customInstance.apiUrl).toURI() - URL(customInstance.frontendUrl).toURI() + val instanceName = binding.instanceName.text.toString() + val apiUrl = binding.instanceApiUrl.text.toString() + val frontendUrl = binding.instanceFrontendUrl.text.toString() + if (instanceName.isNotEmpty() && apiUrl.isNotEmpty() && frontendUrl.isNotEmpty()) { + if (apiUrl.toHttpUrlOrNull() != null && frontendUrl.toHttpUrlOrNull() != null) { query { - Database.customInstanceDao().insertAll(customInstance) + Database.customInstanceDao() + .insertAll(CustomInstance(instanceName, apiUrl, frontendUrl)) } ActivityCompat.recreate(requireActivity()) dismiss() - } catch (e: Exception) { - // invalid URL - Toast.makeText( - context, - getString(R.string.invalid_url), - Toast.LENGTH_SHORT - ).show() + } else { + Toast.makeText(requireContext(), R.string.invalid_url, Toast.LENGTH_SHORT) + .show() } } else { // at least one empty input - Toast.makeText( - context, - context?.getString(R.string.empty_instance), - Toast.LENGTH_SHORT - ).show() + Toast.makeText(requireContext(), R.string.empty_instance, Toast.LENGTH_SHORT).show() } }