Android + Spring + RestTemplate + XML Integration Example

By Arvind Rai, November 02, 2014
This page will provide the example to integrate android and spring to use REST API with RestTemplate that will consume XML data. We are using maven build for spring dependency. Android manifest needs INTERNET permission to access HTTP URL. While writing activity class we have to avoid NetworkOnMainThreadException because android does not allow to build any connection within main thread. Android does this because connection waiting time blocks UI. Find the example step by step.

Create Activity with RestTemplate and SimpleXmlHttpMessageConverter

Find the activity class which is using Spring API to consume REST XML.
PersonActivity.java
package com.concretepage.android;
import org.springframework.http.converter.xml.SimpleXmlHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.widget.TextView;
public class PersonActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        start();
    }
    private void start() {
        final String url = "http://192.178.0.100:8080/person";
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(new SimpleXmlHttpMessageConverter());
        Person person = restTemplate.getForObject(url, Person.class);
        TextView textView = (TextView) this.findViewById(R.id.text_view);
        textView.setText("Hello "+ person.getName());
    }
} 
RestTemplate : RestTemplate is a spring class that is used to access data from RESTful Webservices. It manages HTTP connections. We only need to provide HTTP URL.
SimpleXmlHttpMessageConverter : This class in spring is used to read and write XML data.

Create Class to Consume XML using REST

Suppose we have to consume below XML.
<person>
    <id>1</id>
    <name>Ram</name>
</person> 
Our equivalent java class will be as below.
Person.java
package com.concretepage.android;
public class Person {
    private int id;
    private String name;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
} 

Avoid NetworkOnMainThreadException

In android main thread does not allow to access data from any connection. As in our example we are fetching XML data from HTTP connection, so we can avoid it using android AsyncTask or using another work around as below.
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy); 

Configure INTERNET permission in AndroidManifest.xml

To access URL from internet, we need to set INTERNET permission in android manifest.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.concretepage.android"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="9" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup ="false"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".PersonActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest> 

Create Android Layout and Strings XML for Demo

Find main layout.
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:id="@+id/text_view"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:textSize="100sp"/>
</LinearLayout>  
Find strings.xml file.
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Android-Spring</string>
</resources> 

Maven Dependency for Android and Spring

Find maven dependency.
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.concretepage</groupId>
    <artifactId>AndroidDemo</artifactId>
    <version>1</version>
    <packaging>apk</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>com.google.android</groupId>
            <artifactId>android</artifactId>
            <version>4.1.1.4</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.android</groupId>
            <artifactId>spring-android-rest-template</artifactId>
            <version>1.0.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.simpleframework</groupId>
            <artifactId>simple-xml</artifactId>
            <version>2.7.1</version>
            <exclusions>
                <exclusion>
                    <artifactId>stax</artifactId>
                    <groupId>stax</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>stax-api</artifactId>
                    <groupId>stax</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>xpp3</artifactId>
                    <groupId>xpp3</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>xmlParserAPIs</artifactId>
                    <groupId>xerces</groupId>
                </exclusion>
            </exclusions>
        </dependency>    
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>com.jayway.maven.plugins.android.generation2</groupId>
                <artifactId>android-maven-plugin</artifactId>
                <version>3.9.0-rc.1</version>
                <configuration>
                    <sdk>
                        <platform>20</platform>
                    </sdk>
                    <deleteConflictingFiles>true</deleteConflictingFiles>
                    <undeployBeforeDeploy>true</undeployBeforeDeploy>
                </configuration>
                <extensions>true</extensions>
            </plugin>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project> 

How to Run and Output

To run the example, we need a URL which should return XML. To achieve it, create a simple person.xml file and put into local server. Our URL is ready. Find the output screen shot.
Android + Spring + RestTemplate + XML Integration Example
Happy Learning.

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us