Prefill EditText according to buildtype

380 views Asked by At

Is it possible to set text in EditText only for a certain buildtype? I want the EditText in the app I'm developing to be prefilled when running the debug buildtype. The only way I see this right now is by checking programmatically if the current the current buildtype is "debug" and call setText().

I was hoping to be able to do this in a cleaner way. Perhaps something like the tools namespace in XML layouts. Any suggestions?

3

There are 3 answers

0
dumazy On BEST ANSWER

Eventually I went with my own way of keeping it clean. I've had a look at Aspect Oriented Programming and made an Aspect with AspectJ.

@Aspect
class PrefillAspect {

    @After("execution(* com.example.aspect.LoginActivity.onCreate(*))")
    fun prefillLoginForm(joinPoint: JoinPoint) {
        try {
            val activity = joinPoint.target as LoginActivity
            activity.findViewById<EditText>(R.id.editEmail).setText("[email protected]")
            activity.findViewById<EditText>(R.id.editPassword).setText("MySecretPassword")
        } catch (e: Throwable) {
            Log.e("PrefillAspect", "prefillLoginForm: failed")
        }
    }

}

I've added this aspect to my src/debug/java folder so this aspect is only applied when a debug build is run. There's no code whatsoever in my main source, so this will never be shipped and the code base remains clean.

I've written an article about this here: https://medium.com/@dumazy/prefill-forms-on-android-with-aspectj-97fe9b3b48ab

1
Nitesh On

You can put some text for different environment in your build.gradel file in buildTypes

//For Development Environment
buildConfigField "String", "text", "\"DEVELOPMENT ENVIRONMENT TEXT\""

//For Live Environment leave it empty
buildConfigField "String", "text", "\"\""

Then in activity directly set it to your edittext without manually checking anything.

etValue.setText(BuildConfig.text);

More preferred solution (For direct XML)

instead of buildConfigField use resValue which will generate a String Resource for different environment when project get rebuilt.

//For Live Environment leave it empty
resValue "string", "text", YOUR_STRING_LIVE

//For Development Environment
resValue "string", "text", YOUR_STRING_DEVELOPMENT

and you can use it directly in xml as

android:text="@string/text"
1
Antonis Lat On

Another solution is to create debug and release folders under your src folder and there keep all the common resources with different values between debug and release version. So you will have:

\src\release\res\values\strings.xml

with

  <string name="your_string">release_value_here</string>

and

\src\debug\res\values\strings.xml

with

  <string name="your_string">debug_value_here</string>

and then in XML

android:text="@string/your_string"