Byron Kiourtzoglou

About Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.

XML Binding with Simple Framework

In this tutorial we are going to see how can we Simple Framewrok for XML Binding in Android.

The basic steps to create a Customized dialog are:

  • Create or download the XML formated file you want to bind it to Android.
  • Create the appropriate classes to map appropriately the XML elements and its corresponding attributes
  • Use the appropriate annotations, e.g. @Root, @Element, @Attribute, @ElementList that reflect the nature of each field
  • Use appropriate annotation parameters, like (name="Query"), (required ="true"), alongside annotations to provide corresponding XML properties of the field
  • Use Simple Framework to read the source XML file, create instances of the class you’ve declared and populate them with the corresponding values from the XML file.

Let’s see how the code looks like:

package com.javacodegeeks.xml.bind;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.javacodegeeks.xml.bind.model.OpenSearchDescription;

public class SimpleExampleActivity extends Activity {

    private static final String url = 

  "http://dl.dropbox.com/u/7215751/JavaCodeGeeks/AndroidFullAppTutorialPart03/Transformers+2007.xml";

    private DefaultHttpClient client = new DefaultHttpClient();

    @Override
    public void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.main);

  try {

String xmlData = retrieve(url);

Serializer serializer = new Persister();

Reader reader = new StringReader(xmlData);

OpenSearchDescription osd = 

    serializer.read(OpenSearchDescription.class, reader, false);

Log.d(SimpleExampleActivity.class.getSimpleName(), osd.toString());

  } 

  catch (Exception e) {

Toast.makeText(this, "Error Occured", Toast.LENGTH_LONG).show();

  }

    }

    public String retrieve(String url) {

  HttpGet getRequest = new HttpGet(url);

  try {

HttpResponse getResponse = client.execute(getRequest);

final int statusCode = getResponse.getStatusLine().getStatusCode();

if (statusCode != HttpStatus.SC_OK) {

    return null;

}

HttpEntity getResponseEntity = getResponse.getEntity();

if (getResponseEntity != null) {

    return EntityUtils.toString(getResponseEntity);

}

  } 

  catch (IOException e) {

getRequest.abort();

Log.w(getClass().getSimpleName(), "Error for URL " + url, e);

  }

  return null;

    }

}
package com.javacodegeeks.xml.bind.model;

import java.util.List;

import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;

@Root
public class OpenSearchDescription {

 @Element(name="Query")
 public Query query;

 @Element
 public int totalResults;

 @ElementList
 public List<Movie> movies;

}
package com.javacodegeeks.xml.bind.model;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;

@Element
public class Query {

 @Attribute
 public String searchTerms;

}
package com.javacodegeeks.xml.bind.model;

import java.util.List;

import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;

@Element(name="movie")
public class Movie {

 @Element(required=false)
 public String score;

 @Element(required=false)
 public String popularity;

 @Element(required=false)
 public String name;

 @Element(required=false)
 public String id;

 @Element(required=false)
 public String biography;

 @Element(required=false)
 public String url;

 @Element(required=false)
 public String version;

 @Element(required=false)
 public String lastModifiedAt;

 @ElementList
 public List<Image> images;

}
package com.javacodegeeks.xml.bind.model;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;

@Element(name="image")
public class Image {

 @Attribute
 public String type;

 @Attribute
 public String url;

 @Attribute
 public String size;

 @Attribute
 public int width;

 @Attribute
 public int height;

 @Attribute
 public String id;

}

 
This was an example of how to use Simple Framework to perform XML Binding in your Android Application.

Related Article:

Related Whitepaper:

Beginning Android Application Development (Free Sample Chapter)

Create must-have applications for the latest Android OS!

The Android OS is a popular and flexible platform for many of today's most in-demand mobile devices. This full-color guide offers you a hands-on introduction to creating Android applications for the latest mobile devices. Veteran author Wei Meng Lee accompanies each lesson with real-world examples to drive home the content he covers. Beginning with an overview of core Android features and tools, he moves at a steady pace while teaching everything you need to know to successfully develop your own Android applications.

Get it Now!  

Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books