I'm creating an app where the user has to insert a serverurl in an EditText field, and that url should be the baseUrl of the retrofit-request. So, my code works as it should when i use a hardcoded baseurl, but the app crashes when I try to pass the value from the Edittext to the baseUrl.
Thats how I tried to pass the value:
object NetworkLayer {
var newUrl: String = ""
val retrofit: Retrofit
get() = Retrofit.Builder()
.baseUrl(newUrl)
.addConverterFactory(GsonConverterFactory.create())
.build()
val myApi: MyApi by lazy {
retrofit.create(MyApi::class.java)
}
val apiClient = ApiClient(myApi)
}
and in my MainActivity:
var serverUrl = binding.et1.text.toString()
button.setOnClickListener {
NetworkLayer.newUrl = serverUrl
viewModel.getServerInformation(headerValue)
}
I get this error message: Error message: Caused by: java.lang.IllegalArgumentException: Expected URL scheme 'http' or 'https' but no scheme was found for.
So probably retrofit uses the empty "" string for the request. Somehow I should send the information to retrofit that when clicking the button the url from the Edittext (et1) is the baseUrl. When I use a seperate class (f.e. class Constants, with a companion object with a const val baseUrl = "hardcoded url") it works also. Can I create a function to inform the retrofit client to use the Edittext as baseUrl and declare it in the onClickListener? or could it be a way to create the retrofit client in a class instead of an object? (using url: String as parameter in the class and adding the edittext as argument in the MainActivity?) Sadly the @Url annotation for Retrofit doesn't work as I have to use also @Header and @Query in the different requests.
Or is there a compeletey different way for doing this?
Hopefully there is someone who can help me.