34

I have searched for some similar questions before posting - however I have a general question when it comes to Android and data binding (and the other answers I check did not really get me much further...). Assume you have a class Vehicle:

public class Vehicle {

private Owner owner;
private String brand;

//getter and setter for above attributes...

}

and here is the Owner class ....

public class Owner {

private String name;

}

Now - I was just recently looking into MVVM (ModelView-ViewModel) pattern as employed by Microsofts WPF. Which got me wondering: Assuming I would want to bind the name property of my owner object which is a child of the Vehicle object - would there be some standard way in Android to achieve this? Also presuming, that I might have to validate input before I can have the Model updated?

I was imagining the following components (assuming MVVM):

  • The View (an Activity) contains no application logic - so its more or less empty
  • A ViewModel would handle the instance of the Vehicle object and perform actions on it
  • The Model itself would look as the code I posted before - totally oblivious to the View and the ViewModel

Now when I add my EditTexts, TextViews and so on to the view, I want them to bind to certain the properties of my context object (Vehicle in this case) ... Mhhh if my question is not clear or you need further informatio do let me know :) thanks in advance.

P.s. I think people familiar with WPF might now what I mean? I myself just read about WPF and found it's a nice way to handle stuff.

P.P.s I am aware of the android binding project but I was wondering if there is a sort of build-in approach in Android or maybe some convention someone is following :) this really is more of a binding-theory question I guess ...

Ready4Android
  • 2,022
  • 2
  • 25
  • 29

8 Answers8

25

Native Data Binding

Google has launched its native Data Binding Library!

https://developer.android.com/tools/data-binding/guide.html

Which lets you write your views as such

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@{user.firstName}"/>

But its event wiring mechanism at this time (rc1 version) can't bind to methods on a class extending from Observable (an exception is thrown when compiling; this is a known bug which will be solved).

And sure the lack of two-way binding (which is not expected to be on the first release) is a big drawback.

Anyway, here's a good sample project to play around with https://github.com/saleeh93/data-binding-samples

Minelli
  • 419
  • 4
  • 6
  • Has someone succeeded in making a two-way binding with Native Data Binding library? – kosiara - Bartosz Kosarzycki Jun 03 '15 at 22:46
  • 1
    @kosiara Two-way data binding is not supported yet. Probably, will be in next version. You can follow the status [here](https://code.google.com/p/android-developer-preview/issues/detail?id=2095&colspec=ID%20Type%20Status%20Owner%20Summary%20Stars). – Ye Lin Aung Jun 04 '15 at 03:23
  • 1
    @kosiara it's not directly possible, but this guy shows one possible approach: https://medium.com/@fabioCollini/android-data-binding-f9f9d3afc761 – Konrad Morawski Sep 06 '15 at 12:39
  • Native data binding is a great step forward, but making it one way is the same as making a car which you can just accellerate but not curb. You always need to have to use that boring method findViewById() .. – Apperside Sep 11 '15 at 10:55
  • 1
    Hi, I used @KonradMorawski's link to understand Data binding and created some Github samples showing various basic examples of data binding. You can check them here http://stackoverflow.com/a/33078797/1979347 – Rohan Kandwal Oct 12 '15 at 10:28
15

There is nothing "baked" into the Android SDK which provides equivalent databinding functionality found in MS WPF. Google is providing a lower level interface for the various devices running Android. To date, higher level application frameworks have not emerged from the Android development community. (IMHO, it would take a monster company like Google to create such a thing, given all the different constraints on a framework for all the various Android devices.)

You could create a set of databinding classes in your own application to handle your needs for the MVVM pattern. The "Databinders" would set the relevant event handlers on Android View objects and run some appropriate method on your ViewModel objects in response. They would also translate change events (that you define) on the ViewModel into the appropriate property assignments on the View objects.

Whether that turns out to be worthwhile for your application is a judgment call. My guess is that it would require more effort to write the Databinder classes than just to hook the lower level View event handlers directly. Frameworks are useful primarily when you didn't have to write them yourself.

randomfactor
  • 479
  • 3
  • 11
  • 1
    I think the "monster company" assessment is correct. There is a surprisingly large amount of complex code for databinding in WPF. – sourcenouveau May 18 '11 at 16:43
  • Thanks for your reply - yes I figured as much :( Briefly after posting the question I started having an idea on how to do it - it resembles what you suggested and I will see how far it gets me :) thanks a lot. – Ready4Android May 19 '11 at 07:49
  • 32
    Coming from WPF/Silverlight/WP7 working on Android feels like arriving back in GUI stoneage - even though MonoDroid greatly eases the pain :) – Oliver Weichhold Nov 11 '11 at 18:56
  • 2
    _Frameworks are useful primarily when you didn't have to write them yourself._ Isn't that precisely the reason why people write frameworks in the first place? – VH-NZZ May 12 '14 at 08:55
  • Google itself is already creating a Data Binding library, see my answer below. – Minelli Oct 15 '15 at 13:52
  • 1
    I was right for 4.5 years. Now, I'm wrong. Dang. That's how the software stack crumbles. – randomfactor Oct 20 '15 at 20:52
14

Well, my Android-Binding project is trying to do data-binding via XML layout. Because there's no build-in method provided by Google (and I can't foresee that Google will do so), that's the reason I started this project.

xandy
  • 27,357
  • 8
  • 59
  • 64
  • 1
    I read about your project and checked it out :) but I think for me somthing simpler might suffice. One thing I noticed was that a lack of comments made it difficult for me to understand all the stuff xD ... – Ready4Android May 20 '11 at 08:28
  • so far I am the only developer in the project, so inline commenting is not on top of my to-dos. Have you tried the tutorials/sample codes? – xandy May 21 '11 at 03:39
  • Yes I did :) - but I was trying to understand the internals - the lack of comments made it a bit difficult - but I guess if you're the only developer and you know what you're doing comments really might not be your first priority... Although adding them later will probably not happen either ;) – Ready4Android May 21 '11 at 09:23
  • as others said it is difficult to establish a real work upon Android Binding library. I tried it and it is good in simple cases but binding for commands not always work even in supplied samples. though it is good as it brings WP7 data binding to android easily. – anonim Apr 20 '12 at 12:58
  • I just started working with android-binding and it looks great. – Ilya Kogan Dec 12 '12 at 22:17
  • @xandy i am not able to run any of your app. all i am seeing is a bunch of branches inside repository, in which none of them have proper library project attached. for example when i try to run dome/trunk/ABGallery is asks for gueei.binding.v30.BinderV30 . i downloaded it from https://code.google.com/p/android-binding/downloads/detail?name=android-binding-v30-0.52.jar&can=2&q= but still classed like EventAggregator are missing :( – Shailendra Singh Rajawat Mar 26 '13 at 04:59
  • We use the AB framework in our project in production, and it simplifies UI related code a lot. – Alex Che Mar 10 '14 at 15:47
  • Looks like Google finally started to think this was a good idea :) https://developer.android.com/tools/data-binding/guide.html – Jason Sperske Jun 02 '15 at 19:54
11

Android M will provide powerful library for data binding!

It's available now in dev-preview version.

It looks amazing inside xml and java files:

<TextView android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@{user.firstName}"
    />

Java bean:

public class User {
   private final String firstName;
   private final String lastName;
   public User(String firstName, String lastName) {
       this.firstName = firstName;
       this.lastName = lastName;
   }
   public String getFirstName() {
       return this.firstName;
   }
   public String getLastName() {
       return this.lastName;
   }
}

Binding:

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.main_activity);
   User user = new User("Test", "User");
   binding.setUser(user);
}
Oleksii K.
  • 5,359
  • 6
  • 44
  • 72
  • 4
    To clarify, although it is in M preview, it is actually part of support library so you can use it till API 7. – yigit May 29 '15 at 01:58
  • Google published Data Binding Guide in their Developer Guide website: https://developer.android.com/tools/data-binding/guide.html – kosiara - Bartosz Kosarzycki May 31 '15 at 12:43
  • 1
    One important caveat is that it's only one directional databinding, so its pretty useless. They are not going to implement two-way binding in v1: https://code.google.com/p/android-developer-preview/issues/detail?id=2095&sort=-stars&colspec=ID%20Type%20Status%20Owner%20Summary%20Stars – Richard Jun 10 '15 at 09:05
  • @Richard while this limitation is surely painful, it's an exaggeration to call it "useless" on that basis. In every typical app there are some read-only / reloadable screens (eg. all sorts of data fetched from API). – Konrad Morawski Sep 06 '15 at 12:42
8

Reading a bit about this topic, I just found RoboBinding, a "data-binding Presentation Model framework" for Android.

Similar to the Android-binding project, you can bind properties (one-way or two-way) and events to your views in XML using an extra namespace.

Although it is no built-in approach either, it might be a great help for you.

VH-NZZ
  • 5,248
  • 4
  • 31
  • 47
saschoar
  • 8,150
  • 5
  • 43
  • 46
  • At this time is my framework of choice for MVVM in Android, even with the new Google Data Binding Library on the radar... – Minelli Oct 15 '15 at 13:54
7

Since you first asked your question, the landscape has changed a lot.
Most importantly Stuart Lodge gave us MVVMCross.

This project provides a cross-platform mvvm mobile development framework built on top of Silverlight for WP7, Mono for Android and MonoTouch for iOS, and the WinRT XAML framework for Windows 8 Store applications This project makes extensive use of Portable Class Libraries to provide maintainable cross platform C# native applications.

It provides data binding in your Views against ViewModels

For example, it enables the following:

<EditText
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    local:MvxBind="{'Text':{'Path':'Query','Mode':'TwoWay'}}" />

Resources:

Github Page: https://github.com/slodge/MvvmCross

Presentation: http://slodge.blogspot.co.uk/2012/12/mvvmcross-video-presentation-xaminar.html

And a very good introductional tutorial: Building Android Apps with MVVM and Data Binding

TimothyP
  • 21,178
  • 26
  • 94
  • 142
5

In addition to Oleksii's answer, for those who want to see a sample project (it seems Google hasn't provided any sample project yet), I just made one and pushed it to GitHub.

A few notes:

  • classpath "com.android.databinding:dataBinder:1.0-rc0" doesn't work for me so I use classpath group: 'com.android.databinding', name: 'dataBinder', version: '1.0-rc0'
  • Need Java 7 +
  • If you get errors, try clean/rebuild.
  • Don't forget to implement android.databinding.Observable or extends BaseObservable if you need the ability to notify when data changes.
  • minSdkVersion is 7. It's a support lib.
  • My project doesn't follow MVVM, it just uses data binding. Added MVVM sample.
Community
  • 1
  • 1
pt2121
  • 11,720
  • 8
  • 52
  • 69
1

I realize this is some years later but faced with the same issues I ran across the following which may help lessen the load.

RoboBinding - handles binding - as mentioned above RoboGuice - does dependency injection

There is a very nice video presentation of RoboBinding that will help explain what and how.

I am not affiliated with either effort but they do look promising for those folks still trying to resolve the binding issues, especially on involved code. RoboBinding also handles bidirectional updates.

Walt Corey
  • 718
  • 7
  • 12