I have an activity from where I'm getting base url ip like 10.0.2.2 and port 8080 through two different EditText
.
Now I'm making a url string from the obtained values like http://10.0.2.2:8080
.
Now I need to set this url as ApiClient()
BASE_URL. This url will be permanent. It should be available all over the app in any activity or any fragment.
NOTE: I need to Set the value only single time of Application Life Time.
If you suggest a Singleton Class
or by SharedPreference
please explain with source. (I've tried with them but it didn't worked perfectly)
Asked
Active
Viewed 687 times
-1

Mehedi Hasan Chonchol
- 75
- 1
- 2
- 10
-
as far as I know we cannot change the base url, but we can alter the url when sending a request, something like this https://stackoverflow.com/questions/32559333/retrofit-2-dynamic-url – stallianz Oct 24 '18 at 20:47
-
I don't want to change the base url. I just need to set the base url on run time when the app runs for the first time taking the values from `EditText` input. – Mehedi Hasan Chonchol Oct 24 '18 at 20:58
-
1you can set the url at the request with @Url parameter, like in this link stackoverflow.com/questions/32559333/retrofit-2-dynamic-url – stallianz Oct 24 '18 at 21:04
-
This is not what I wanted. Thanks – Mehedi Hasan Chonchol Oct 26 '18 at 09:27
2 Answers
0
You can make a class and define static variables with better and better. And initialize those variable when you get value from edit text and then you can simply get value from that static And in your activity class you access like this baseurl.Setip(your edit text value) And to get that ip you can write Retrofit.Builder.baseurl(baseurl.getIp) Something like this Hope this image will explain you

Khalid Saeed
- 131
- 2
- 8
-
I tried it. This process works only for the first time. But after the app destroys the information is lost. So better to use SQLite Database or store the information in a File in phone storage. BTW thanks for your answer. – Mehedi Hasan Chonchol Oct 25 '18 at 07:11
-
then you can use SharedPreferences for storing this url and if you want i can share the syntax to store and retrive sharedpreference – Khalid Saeed Oct 26 '18 at 12:45
-
Shared preference is only accessible from Activity. So in this case you can't get value from shared preference. – Mehedi Hasan Chonchol Oct 26 '18 at 16:14
-
@Mehedi shared preference can also be accessed from a java class just need to Extend with context – Khalid Saeed Oct 30 '18 at 13:21
0
For the above problem, best solution is to store the information in SQLite
or Room
Database or manually store the information in a file in Phone Storage.
Using SharedPreferences
it can be done also. In this case the ApiClient
should have a Parameter.

Mehedi Hasan Chonchol
- 75
- 1
- 2
- 10