0

Often there's a scenario where there's a number of UI fields that have to be copied into Model objects. For instance, I'm currently writing a cart page that accepts credit card information in an Activity and I need to write all the inputted values to a CreditCard object.

I end up with blocks of code that look like the following:

      CreditCard card  = new CreditCard();
      card.setFullName(txtFullName.getText().toString());
      card.setAddress(txtStreetAddress.getText().toString());
      card.setCity(txtCity.getText().toString());
      card.setState((String) spinnerState.getSelectedItem());
      card.setZip(txtZip.getText().toString());
      card.setPhone(txtPhone.getText().toString());
      card.setMonth(txtMonth.getText().toString());
      card.setYear(txtYear.getText().toString());
      card.setNumber(txtNum.getText().toString());
      card.setCvv(txtcvv.getText().toString());

I've tried to come up with a way via UI tags in XML or other means to simplify/automate this process but I can't come up with an efficient means. Am I missing out on something?

StackOverflowed
  • 5,854
  • 9
  • 55
  • 119
  • Seems like you need a data binding feature. Take a look at this SO question http://stackoverflow.com/questions/6007941/android-data-binding-similar-to-wpf it contains useful resources for what you are asking for – Agustin Meriles Apr 30 '15 at 18:40

1 Answers1

1

Unfortunately, there isn't anything hard-wired into Android that will let you bind large chunks of data (as shown in your example) from UI in an elegant way, yet.

One thing you can do to make your code cleaner/more testable is "injecting" the fields i.e. "txtFullName.getText().toString()" into the CreditCard constructor. That way, you do not have superfluous "setter" code like you do in your example. However, you would still have a block of code when instantiating the Credit Card object:

CreditCard card = new CreditCard(arg1, arg2, arg3, arg4..etc)

Another thing you can do is use a dependency injection (DI) framework like Dagger. Dagger does the "injecting" of fields for you in Module(s) that you specify for your class(es), "behind the scene".

http://square.github.io/dagger/

EDIT: check out the new data binding feature released in Android Studio 1.3 (currently Beta)

Virat Singh
  • 1,464
  • 1
  • 12
  • 16