How do I update the BASE_URL defined in my gradle through UI?

时间:2019-04-17 00:42:38

标签: android android-edittext sharedpreferences android-alertdialog android-buildconfig

I am currently working on creating an alertdialog box with edittext in it which opens on tap on my login screen , which should allow the capability to update the BASE_URL defined in my gradle. Say for instance I am currently defining my base_url as follows:

 buildConfigField("String", "BASE_URL", "\"https://myapp.com/api\"")

which upon running the app translated to a buildConfig URL such that in Buildconfig.java it shows as :

  public static final String BASE_URL = "https://myapp.com/api";

Now my question is ,how do I update this base url on the edit text box i add in the alertdialog on the login screen, such that if i change the edit text text to :

https://myapp.com/api2

upon clicking save it should save the new entry and apply it to buildconfig file throughout the course of the app. I also want to display a reset button to allow the capability to reset this URL back to the original. Any ideas how to go about it?

am using a similar code for alertdialog as this : https://medium.com/@mujtahidah/custom-dialog-with-edittext-and-button-action-android-fc64ef5eb2b2

Just want to know if there is a way BASE_URL can be updated in the UI dynamically and saved on the fly? Any ideas or examples? Thanks in advance!

2 个答案:

答案 0 :(得分:1)

Your question itself has the answer.

  • Just want to know if there is a way BASE_URL can be updated in the UI dynamically and saved on the fly?
  • answer: No

Generated BuildConfig.java file contains all static and final fields.

public static final String BASE_URL = "https://myapp.com/api";

In java you can't change the final fields.

Suggestion: On taping of save button in your alert dialog save the updated URL in instance variable(which will be gone on closing the application) or store in SharedPreferences(which will be available even after reopening the application). So that you can use the Variable wherever you want in further.

答案 1 :(得分:0)

So basically BuildConfig is a generated file, which happens at compile time. So if you want to use a value that you are setting at Runtime, you should probably use something in Memory, or use a shared preferences. You cannot edit a compile-time generated file during runtime.

SharedPreferences prefs = this.getSharedPreferences(
      "com.example.app", Context.MODE_PRIVATE);


prefs.edit().putString("base_url", "your new base url").apply();


String baseUrl = prefs.getString("base_url", BuildConfig.BASE_URL); 
// BuildConfig.BASE_URL being your default value