Wednesday, December 14, 2011

XML Data Binding for Java on Android using JiBX

JiBX is an excellent tool for binding XML data to Java objects on the Android platform.

- JiBX is fast!
- JiBX has a small footprint (it will add only 60KB to your .apk)
- JiBX uses the Android XMLPull parser by default
- It's easy to use!

We all appreciate the advantages of being able to use java classes to do data manipulation. person.setFirstName("Don"); is much easier then messy DOM manipulation: document.getElementsByTagName("first").item(0).appendChild(document.createTextNode("Don"));

Let's create a sample project.

First, create java bindings for your XML schema using JiBX, or select a pre-build schema library.

For this example, we'll use a pre-built binding from the JiBX schema library. Our sample xsd file is an XML definition which includes a person's first and last name.

Click here to see our sample schema in the JiBX library. You may want to take a look at the schema and the JiBX generated java source code.

Download the java jar file by right-clicking this
link and select 'save as'.

Next, download the jibx runtime jar file by right-clicking this link and select 'save as'. We'll need these jars shortly.

Now we're ready to create our Android application. First you need to install eclipse and the Android SDK.

From Eclipse, select New -> Project -> Android Project.

I'm calling this project 'jibxapp'.

On the next screen, select your target api.


Finally, enter your java package name.


You project should appear in your workspace.

Navigate to jibxapp -> res -> layout and double-click main.xml to bring up the form editor.


Add a button, two medium static text fields, two data text boxes, and a multi-line text box so your screen looks something like this:


You may want to test your Android emulator here by right clicking the project name and selecting 'Debug as' -> 'Android Application'.

To add your java binding and the JiBX runtime, right-click your project name and select properties. Click 'java build path' -> Libraries -> 'Add external jars' and add the two jars that we downloaded earlier.


Navigate and open your Android source code file.


Add this test code to your java source file:

package org.jibx.android.test;

import java.io.ByteArrayOutputStream;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;

import org.jibx.runtime.BindingDirectory;
import org.jibx.runtime.IBindingFactory;
import org.jibx.runtime.IMarshallingContext;
import org.jibx.runtime.IUnmarshallingContext;
import org.jibx.runtime.JiBXException;
import org.jibx.schema.org.jibx.sampleschema.person.Person;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class JibxappActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

mPickDate = (Button) findViewById(R.id.button1);
mFirstName = (EditText) findViewById(R.id.editText1);
mLastName = (EditText) findViewById(R.id.editText2);
mTextBox = (EditText) findViewById(R.id.editText3);
// add a click listener to the button
mPickDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(android.view.View v) {
doJibxTest();
}
});
}

Button mPickDate = null;
EditText mFirstName = null;
EditText mLastName = null;
EditText mTextBox = null;

/**
* Add the test table records.
*/
public void doJibxTest() {
Person person = new Person();
person.setFirstName(mFirstName.getText().toString());
person.setLastName(mLastName.getText().toString());


String xml = marshalMessage(person);
mTextBox.setText(xml);

Person personOut = (Person) unmarshalMessage(xml);

mPickDate.setText(personOut.getFirstName() + ' ' + personOut.getLastName());
}

/**
* Marshal this message to xml .
*
* @param message
* @param system
* @return
*/
public final static String STRING_ENCODING = "UTF8";
public final static String URL_ENCODING = "UTF-8";
String bindingName = "binding";

public String marshalMessage(Object message) {
try {
IBindingFactory jc = BindingDirectory.getFactory(bindingName, Person.class);
IMarshallingContext marshaller = jc.createMarshallingContext();
ByteArrayOutputStream out = new ByteArrayOutputStream();
marshaller.marshalDocument(message, URL_ENCODING, null, out);
return out.toString(STRING_ENCODING);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (JiBXException e) {
e.printStackTrace();
}
return null;
}

/**
* Unmarshal this xml Message to an object.
* @param xml
* @param system
* @return
*/
public Object unmarshalMessage(String xml) {
try {
IBindingFactory jc = BindingDirectory.getFactory(bindingName, Person.class);
IUnmarshallingContext unmarshaller = jc.createUnmarshallingContext();
return unmarshaller.unmarshalDocument(new StringReader(xml), bindingName);
} catch (JiBXException e) {
e.printStackTrace();
}
return null;
}
}


This program takes the First and Last Name entered, plugs them into a java data object, marshals the object to xml, and unmarshals the xml back to a data object and extracts the data from it. I made this program very simple, of course you would not do this kind of processing in the main thread.

Run your application by right clicking the project name and selecting 'Debug as' -> 'Android Application'. Enter your first and last name and click the button on the top.


VoilĂ !

27 comments:

Don Corley said...

You can find this project in the JiBX source repository at:
https://github.com/jibx/schema-library/tree/master/schema-utilities/examples/android/jibxapp

Maris Boyd said...

In Android Development,it doesn't perform bytecodes. Android's java runtime uses a register based virtual machine that completes .dex information instead of class information. Theoretically you could generate those instead of java bytecode.

william said...

First, I think the author did a great job to make JiBX work on Android, however, JiBX was originally designed for desktop and server side development, hence it's too heavy-weight for resource limited mobile device like Android. I would recommend a light-weight xml binding framework tailed for Android platfrom, the library is called Nano, the jar is less than 70K, performance comparable to Android native parser like SAX and Xml Pull, it supports both XML and Json binding, it uses annotation driven binding, similar to JAXB, also it provides a binding compiler to auto-generate bindable class from xml schema, you may have a try if you are interested in it.
https://github.com/bulldog2011/nano

Don Corley said...

William,
Actually JiBX was designed to be small and fast. It uses the xmlpull parser which is built into Android. It is perfect for the Android platform.

Gal Levinsky said...

Thanks for the detailed article!

After failing with some Java XML projects, JiBX did the work.

Thank you.

Gal Levinsky said...

Just as a side note, for anyone who with to have a generic (un)marshal methods:

public static String marshalMessage(T message, Context ctx) {
try {
IBindingFactory jc = BindingDirectory.getFactory(bindingName, message.getClass());
IMarshallingContext marshaller = jc.createMarshallingContext();
ByteArrayOutputStream out = new ByteArrayOutputStream();
marshaller.marshalDocument(message, URL_ENCODING, null, out);
return out.toString(STRING_ENCODING);
}catch (Exception e){
e.printStackTrace();
}
return null;
}



public static T unmarshalMessage(String xml, Class T) {
try {
IBindingFactory jc = BindingDirectory.getFactory(bindingName, T);
IUnmarshallingContext unmarshaller = jc.createUnmarshallingContext();
return (T) unmarshaller.unmarshalDocument(new StringReader(xml), bindingName);
} catch (JiBXException e) {
e.printStackTrace();
}
return null;
}

Emi Jackson said...

Hi, I am Emi lives in Chennai. I am technology freak. I did Android mobile application development course in Chennai at reputed training institutes, this is very usful for me to make a bright carrer in IT industry. So If you looking for best Android Training Institutes in Chennai please visit fita academy. Android Training in Chennai


Emi Jackson said...

Hi I am Emi from Chennai. Thanks for sharing the informative post about Java technology. It’s really useful for me to know more about this technology. Recently I did Java Training in Chennai at a leading Java Training Institutes in Chennai.

kovalan Jayamurugan said...

Thanks for your article on Android technology. Android is an open source platform that allows developers to create stunning website loaded with various advanced features and functionalities. Best Android Training institute in Chennai

kovalan Jayamurugan said...

Excellent post!!! Java is most popular and efficient programming language available in the market today. It helps developers to create stunning desktop/web applications loaded with stunning functionalities. Best JAVA Training in Chennai

Rahul said...

That’s a great article. But there is more to do if you learn Android. Just try visiting our page!
Android Training Chennai

murali karthik said...

In near future, big data handling and processing is going to the future of IT industry. Thus taking Hadoop Training in Chennai | Big Data Training in Chennai will prove beneficial for talented professionals.

Srishthi B said...

That is a brilliant article on dot net training in Chennai that I was searching for. Helps us a lot in referring at our dot net training institute in Chennai. Thanks a lot. Keep writing more on dot net course in Chennai, would love to follow your posts and refer to others in dot net training institutes in Chennai.

Steve Smith said...

Great and Useful Article.

Online Java Training

Online Java Training from India

Online Java Training

Online Java Training From India

Java Training Institutes in Chennai

Java Training in Chennai

Gopi Perumal said...

Quite Interesting post!!! Thanks for posting such a useful post. I wish to read your upcoming post to enhance my skill set, keep blogging.

Regards,
CCNA Training in Chennai | CCNA Training Institute in Chennai | Best CCNA Training in Chennai

Melisa said...

Nice tutorial on android technology hats-off to your effort. Your article explained the potential of android technology in coming years. Android Training in Chennai|iOS Training in Chennai |Android training

Training Chennai said...

Fantastic post...Android Training in Chennai | Best Android Training in Chennai | Android Training

Bay Max said...

Excellent post.You gave a detailed explanation.
Thanks
DOT NET Course Chennai
| DOT NET Training Institute in Chennai

Andrew Son said...

Hadoop is especially used for Big Data maintenance. It uses Hadoop distributed file system . Its operating system is in cross platform. Its framework mostly written in java programming language. The other languages which are used by hadoop framework are c, c++ (c with classes) and sometimes in shell scripting.Thank you..!!
regards,
Hadoop Training in Chennai | hadoop training in adyar

Paul Miller said...

Wonderful post!!Java is written once and used anywhere, means general it is platform independent so it can run any platform like in android, linux, etc..,.It Is general purpose programming language. It was Origin by two programming language c and c++(c with classes).Thank you for sharing your article.
Regards,
java training in vadapalani | JAVA Training in Chennai

John Alert said...

I have read your blog its very attractive and impressive. I like it your blog.


JavaEE Training in Chennai JavaEE Training in Chennai

Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

Java Online Training Java Online Training Core Java 8 Training in Chennai Java 8 Training in Chennai

John Alert said...

Hibernate Online Training Hibernate Online Training Hibernate Training in Chennai Hibernate Training in Chennai Java Online Training Java Online Training Hibernate Training Institutes in ChennaiHibernate Training Institutes in Chennai

Melisa said...

Thanks Admin for sharing such a useful post, I hope it’s useful to many individuals for whose looking this precious information to developing their skill.
Regards,
Android Training in Chennai|Android Course in Chennai|Android Training Chennai|iOS Training|iOS Course in Chennai

Metaforum Tech said...

Mettur dam updates Mettur Dam

Mettur dam updates Mettur

Mehgna Sharma said...

Nice post Thanks for the Sharing this information Big Data Hadoop Training | PHP Training in Noida

raj kumar said...

Hi I am from Chennai. Thanks for sharing the informative post about Android technology. It’s really useful for me to know more about this technology. Recently I did Android Training in Chennai.


Android Training in Chennai

Charlie Hamilton said...

I love reading through your blog, I wanted to leave a little comment to support you and wish you a good continuation. Wish you best of luck for all your best efforts. I want to share some information, we provide outsource data entry services in all over the world.
Back Office Services