Tuesday, November 26, 2013

RoboSpice Spring

Robospice Spring Android module is a library that you can use when you need to handle restful network communication on your application. Recently, it has been highly advised to use a dependency manager to add this library to your projects. Since the official documentations already contain plenty of guides for that, I will just skip that part. For this tutorial, just make sure that you have the needed jar files. Here are the list of jars:

robospice-cache-x.y.z.jar
robospice-x.y.z.jar
commons-io-x.y.z.jar
commons-lang3-x.y.z.jar
spring-android-core-x.y.z.jar
spring-android-rest-template-x.y.z.jar
robospice-spring-android-x.y.z.jar

These optional libraries are also useful:

jackson-core-asl-x.y.z.jar
jackson-mapper-asl-x.y.z.jar 
jackson-databind-x.y.z.jar
gson-x.y.z.jar
simple-xml-x.y.z.jar

Update the application manifest by adding these permissions:
1:    <uses-permission android:name="android.permission.INTERNET"/>  
2:    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>  
3:    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>  

Also add the JacksonSpringAndroidSpiceService within the application section of the manifest:
1:  <service android:name="com.octo.android.robospice.JacksonSpringAndroidSpiceService" android:exported="false" />  

For the WebService, we will use the OpenWeatherMap forecast api samples. To handle the api response data, we need to prepare the necessary classes but first we need to take a look at the json object from the server.


As you can see, each list item consists of several fields. Some fields consist of strings while others are composed of json objects or json array. For the json objects like the temp property, we prepare an object to handle its data:
1:  @JsonIgnoreProperties(ignoreUnknown = true)  
2:  public class Temp {  
3:       private String day;  
4:       private String min;  
5:       private String max;  
6:       private String night;  
7:       private String eve;  
8:       private String morn;  
9:       public String getDay() {  
10:            return day;  
11:       }  
12:       public void setDay(String day) {  
13:            this.day = day;  
14:       }  
15:       public String getMin() {  
16:            return min;  
17:       }  
18:       public void setMin(String min) {  
19:            this.min = min;  
20:       }  
21:       public String getMax() {  
22:            return max;  
23:       }  
24:       public void setMax(String max) {  
25:            this.max = max;  
26:       }  
27:       public String getNight() {  
28:            return night;  
29:       }  
30:       public void setNight(String night) {  
31:            this.night = night;  
32:       }  
33:       public String getEve() {  
34:            return eve;  
35:       }  
36:       public void setEve(String eve) {  
37:            this.eve = eve;  
38:       }  
39:       public String getMorn() {  
40:            return morn;  
41:       }  
42:       public void setMorn(String morn) {  
43:            this.morn = morn;  
44:       }  
45:  }  

For an array type (just like the weather list) we do declare it like this:
1:       private List<Weather> weather;  

For our request to the webservice, we prepare the following request object:
1:  public class ForecastListRequest extends SpringAndroidSpiceRequest<ForecastList> {  
2:       public ForecastListRequest() {  
3:            super(ForecastList.class);  
4:       }  
5:       @Override  
6:       public ForecastList loadDataFromNetwork() throws Exception {  
7:            Uri.Builder builder = Uri.parse("http://api.openweathermap.org/data/2.5/forecast/daily?lat=35&lon=139&cnt=7&mode=json").buildUpon();  
8:            return getRestTemplate().getForObject(builder.build().toString(), ForecastList.class);  
9:       }  
10:  }  

After preparing the objects, we need to instantiate our spiceManager in our activity to be able to use it:

1:  private SpiceManager spiceManager = new SpiceManager(JacksonSpringAndroidSpiceService.class);  

Also we need to start it on the onStart method of the activity before using it:
1:       @Override  
2:       protected void onStart() {  
3:            super.onStart();  
4:            spiceManager.start(this);  
5:       }  

And stop the spiceManager when the activity stops:
1:       @Override  
2:       protected void onStop() {  
3:            spiceManager.shouldStop();  
4:            super.onStop();  
5:       }  

In our onCreate method, we execute the request like this:
1:  ForecastListRequest request = new ForecastListRequest();  
2:            spiceManager.execute(request, new RequestListener<ForecastList>() {  
3:                 @Override  
4:                 public void onRequestFailure(SpiceException arg0) {  
5:                      Log.i("ForecastListRequest", "failed");  
6:                 }  
7:                 @Override  
8:                 public void onRequestSuccess(ForecastList arg0) {  
9:                      Log.i("ForecastListRequest", "success!");  
10:                      List<Forecast> list = arg0.getList();  
11:                      for (Forecast forecast : list) {  
12:                           Log.i("ForecastListRequest", "dt=" + forecast.getDt());  
13:                      }  
14:                 }  
15:            });  

The full source code for this tutorial can be downloaded here

4 comments:

  1. Perfect,
    thanks.
    How do you handle usually all the dependencies?
    Do you use gradle, or something else?

    ReplyDelete
    Replies
    1. Hi,

      When I made the tutorial, I manually setup the library. I prefer maven to gradle though, maybe just because I use it more on other java projects.

      Delete
  2. 014-07-03 19:09:15 - Dex Loader] Unable to execute dex: Multiple dex files define Lorg/apache/commons/lang3/builder/ToStringStyle;
    [2014-07-03 19:09:15 - RSExample] Conversion to Dalvik format failed: Unable to execute dex: Multiple dex files define Lorg/apache/commons/lang3/builder/ToStringStyle;

    ReplyDelete
  3. Your very own commitment to getting the message throughout came to be rather powerful and have consistently enabled employees just like me to arrive at their desired goals.

    Best PHP Training Institute in Chennai|PHP Course in chennai
    Best .Net Training Institute in Chennai
    Dotnet Training in Chennai
    Dotnet Training in Chennai

    ReplyDelete