RESTful Web Service with Spring for Android

Tutorial for consuming RESTful web services With Spring for Android.

In this article, we will be talking about RESTful Web Service with Spring for Android that how to consume Restful Web service using Android client. But, before we start, we will talk about RestFul Web Service.

RestFul Web Service.

Representational State Transfer (REST) is a type of webservice. For example, the uniform interface, that if connected to a web benefit initiate alluring properties, like execution, adaptability, and modifiability, that empower administrations to work best on the Web. In the REST structural style, information and usefulness are considered assets and are utilizing Uniform Resource Identifiers (URIs) ordinarily, connects on the Web. The assets are followed up on by utilizing an arrangement of basic, all around characterized operations. The REST structural style obliges an engineer to a customer/server design and is intended to utilize a stateless correspondence convention, ordinarily HTTP. In the REST engineering style, customers and servers trade representations of assets by utilizing an institutionalized interface and convention.


TUTORIAL:

This Getting Started direct strolls you through the way toward RESTful Web Service with Spring for Android and building an application that utilize Spring for Android’s RestTemplate to get a Spring MVC-based RESTful web benefit.

What is Spring?

Spring for Android is a framework that is designed to provide components of the Spring family of projects for use in Android apps. Like all Spring projects, the real power of Spring for Android is found in how easily it can be extended.
Features

  • A Rest Client for Android
  • Authentication  support for accessing secure APIs

Building RESTful Web Service with Spring for Android:

In this tutorial of RESTful Web Service with Spring for Android you will build an Android customer that devours/consumes a Spring-based RESTful web benefit. In particular, the customer will devour the administration made in Building a RESTful Web Servce.
The service will going to respond with a JSON representation of some data i.e contacts

{"id":1,"content":"Contacts", "name":"Harris", "number":123456789, "email": "abc@xyz.com"}

The Android client will renders the following data into a view:
(ID, content,Name, Number and email )

Create an Android project:

Open Android Studio, Create Project. On the off chance that you favor, you can utilize the Project in the underlying envelope and skip ahead to Create a representation class. When you are done, you can contrast your code with the total envelope and Run the customer. Utilize “RestFulSpring” for the application and module names, and alter the bundle name to be “icoderslab.com.restfulspring”. Enter the area of your deciding for the venture and leave the various choices with their default settings.

RESTful Web Service with Spring for Android

The following screen displays a choice to choose the sort of movement to utilize. Select “Empty Activity” and proceed.RESTful Web Service with Spring for Android

The last screen presents some fields for setting the activity, layout, and fragment names. Again, continue with the default options to finish the project setup.create-project4

At the point when the Project is made, you will see that few files are included automatically.

project-contents

To complete this guide, you will edit the following:

  •  Restfulservice/src/main/AndroidManifest.xml
  • Restfulservice/src/main/res/values/strings.xml
  • Restfulservice/src/main/res/layout/fragment_main.xml
  • Restfulservice/src/main/res/menu/main.xml
  • Restfulservice/build.gradle
  • Restfulservice/src/main/java/com/icoderslab/restfulservice/MainActivity.java

 

Change in Android Manifest :

When you made the Project, AndroidManifest.xml was automatically added with an essential execution. The Android Manifest contains all the data required to run an Android application.

Include the INTERNET consent so the application can get and send data over the web.

Restfulservice/src/main/AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="icoderslab.com.restfulservice">

<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity"
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>

 

Make string assets :

Content strings can be referenced from the application or from other asset records. This guide utilizes eight content perspectives and a menu thing, and each of these UI components needs a content depiction. To start with, expel the hello_world and action_settings strings. When you made the venture, it incorporated these. These are not utilized for this guide and can be evacuated. Next, include id_label, id_value, content_label, content_value,name_label, name_value,email_label,email_value,num_label,num_value and action_refresh strings for each UI gadget separately.

Restfulservice/src/main/res/values/strings.xml


<resources>
<string name="app_name">RestFulService</string>
<string name="id_label">The ID is</string>
<string name="id_value">[id]</string>
<string name="content_label">The Content is</string>
<string name="content_value">[content]</string>
<string name="name_label">Name</string>
<string name="name_value">[Name]</string>
<string name="num_label">Nummber</string>
<string name="num_value">[Number]</string>
<string name="email_label">Email</string>
<string name="email_value">[Email]</string>
<string name="action_refresh">Refresh</string>
</resources>


Make a format/Create a Layout:

The format document is the place you characterize the visual structure for the UI of your application. When you made the Project, Android Studio included a design part. As the name infers, a format section speaks to a bit of the general design. For this situation the design piece is utilized to show some content inside the principle movement. Expel the current “Hello world!” TextView that was included when you made the venture. At that point alter the format piece to incorporate four TextView widgets. The ids are utilized to reference these widgets from the code. Take note of the utilization of the string assets for the content of every widgets.

Restfulservice/src/main/res/layout/fragment_main.xml


<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity$PlaceholderFragment">

<TextView

android:id="@+id/id_label"
android:text="@string/id_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

<TextView
android:id="@+id/content_label"
android:text="@string/content_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:layout_below="@+id/id_label"
android:layout_alignParentLeft="true" />
<TextView
android:id="@+id/name_label"
android:text="@string/name_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:layout_below="@+id/content_label"
android:layout_alignParentLeft="true" />
<TextView
android:id="@+id/num_label"
android:text="@string/num_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:layout_below="@+id/name_label"
android:layout_alignParentLeft="true" />
<TextView
android:id="@+id/email_label"
android:text="@string/email_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:layout_below="@+id/num_label"
android:layout_alignParentLeft="true" />

<TextView
android:id="@+id/id_value"
android:text="@string/id_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/id_label"
android:layout_marginLeft="50dp" />

<TextView
android:id="@+id/content_value"
android:text="@string/content_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/content_label"
android:layout_alignLeft="@+id/id_value" />
<TextView
android:id="@+id/name_value"
android:text="@string/name_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:layout_below="@+id/content_label"
android:layout_alignLeft="@+id/id_value" />
<TextView
android:id="@+id/num_value"
android:text="@string/num_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:layout_below="@+id/name_label"
android:layout_alignLeft="@+id/id_value" />
<TextView
android:id="@+id/emai_value"
android:text="@string/email_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:layout_below="@+id/num_label"
android:layout_alignLeft="@+id/id_value" />

</RelativeLayout>

The format incorporates some data about how to position and size the widgets. Android Studio will show the visual representation of the format in the preview window

fragment


Create a menu:
The project includes a menu for the main activity with an existing “Settings” option. Remove the “Settings” menu option and add the “refresh” option. Note again the use of the string resource as the title of the menu item.
Restfulservice/src/main/res/menu/main.xml


<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity" >

<item android:id="@+id/action_refresh"
android:title="@string/action_refresh"
android:orderInCategory="100"
app:showAsAction="never" />>

</menu>

Android Studio will display the visual representation of the menu in the preview window:

RESTful Web Service with Spring for Android


Create a representation class:
To model the JSON data received from the RESTful HTTP request, you create a representation class that defines the fields. Navigate to the “com.icoderslab.restfulspring” package in the Project navigator. Select “New…” from the “File” menu.

RESTful Web Service with Spring for Android

add the info such that content ,id name, num etc


package icoderslab.com.restfulservice;

/**
* Created by harris on 11/16/2016.
*/
public class Info {

private String id;
private String content;
private String name;
private String num;
private String emil;

public String getId() {
return this.id;
}

public String getContent() {
return this.content;
}

public String getName() {
return this.name;
}

public String getNum() {
return this.num;
}

public String getEmail() {
return this.emil;
}
}


Add dependencies:

To utilize Spring for Android’s RestTemplate within an Android app, you need to add the required Maven dependencies to the Gradle build file. RestTemplate makes use of Jackson, which is a powerful JSON processor for Java.
Restfulservice/build.gradle.

apply plugin: 'com.android.application'

android {
compileSdkVersion 25
buildToolsVersion "25.0.0"

defaultConfig {
applicationId "icoderslab.com.restfulservice"
minSdkVersion 17
targetSdkVersion 25
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:25.0.0'
compile 'org.springframework.android:spring-android-rest-template:1.0.1.RELEASE'
compile 'com.fasterxml.jackson.core:jackson-databind:2.3.2'
}
packagingOptions {
exclude 'META-INF/NOTICE' // will not include NOTICE file
exclude 'META-INF/LICENSE' // will not include LICENSE file
// as noted by @Vishnuvathsan you may also need to include
// variations on the file name. It depends on your dependencies.
// Some other common variations on notice and license file names
exclude 'META-INF/notice'
exclude 'META-INF/notice.txt'
exclude 'META-INF/license'
exclude 'META-INF/license.txt'
}
}

Create an activity:

The Model-View-Controller design pattern (MVC) is used extensively in Android applications. An Activity controls the view, which is represented by the layout you already created. When you created the project, a MainActivity was also created with a default implementation. Modify the MainActivity to make a RESTful HTTP request and update the view. Each modification is explained below.

Restfulservice/src/main/java/com/icoderslab/restfulservice/MainActivity.java


package icoderslab.com.restfulservice;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

if (savedInstanceState == null) {

getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}

@Override
protected void onStart() {
super.onStart();
new HttpRequestTask().execute();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_refresh) {
new HttpRequestTask().execute();
return true;
}
return super.onOptionsItemSelected(item);
}

/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {

public PlaceholderFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment, container, false);
return rootView;
}
}

private class HttpRequestTask extends AsyncTask<Void, Void, Info> {
@Override
protected Info doInBackground(Void... params) {
try {
final String url = "www.example.com"; // the  url from where to fetch data(json)
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
Info info = restTemplate.getForObject(url, Info.class);
return info;
} catch (Exception e) {
Log.e("MainActivity", e.getMessage(), e);
}

return null;
}

@Override
protected void onPostExecute(Info info) {
TextView infoIdText = (TextView) findViewById(R.id.id_value);
TextView infoNameText = (TextView) findViewById(R.id.name_value);
TextView infoContentText = (TextView) findViewById(R.id.content_value);
TextView infoNumText = (TextView) findViewById(R.id.num_value);
TextView infoEmailText = (TextView) findViewById(R.id.emai_value);

infoNumText.setText(info.getNum());
infoNameText.setText(info.getName());
infoIdText.setText(info.getId());
infoContentText.setText(info.getContent());

infoEmailText.setText(info.getEmail());
}

}
}

In the first place, include the HttpRequestTask private class. This class acquires from AsyncTask which is a faciltiy given by Android to performing possibly, long running exercises off the main UI thread.

Spring gives a format class called RestTemplate. RestTemplate makes interfacing with most RESTful administrations a basic procedure. Inside the doInBackground technique for the HttpRequestTask class, RestTemplate is utilized to make a HTTP ask for and marshal the JSON reaction to a Greeting object. At the point when doInBackground gives back, the onPostExecute Method is called, where the content estimations of the IdText, NameText, NumberText,EmailText and ContentText widgets are Results with the aftereffects of the HTTP Request.

Next, include the onStart technique which calls the execute strategy on HttpRequestTask. The onStart strategy is a piece of the Activity lifecycle and is called when the movement begins. The outcome is that the HTTP ask for is performed when the application loads.

Ultimately, redesign the onOptionsItemSelected technique to likewise execute the HTTP ask for when the “Refresh” menu thing is chosen. This permits you to make extra HTTP asks for without shutting and restarting the application.


Run the Project :

You can now run the application from Android Studio. To do this, tap the play button (green triangle) in the toolbar of Android Studio. An exchange box will show up requesting that you select the device on which to run the application. You should have an Android device or emulator designed with a specific end goal to run the application. You are done with your RESTful Web Service with Spring for Android.

RESTful Web Service with Spring for Android

Download Code

BY Harris Das

Leave a Reply

Your email address will not be published. Required fields are marked *