Need sample Android REST Client project which implements Virgil Dobjanschi REST implementation pattern

39,242

Solution 1

OverView

Edit:

Anyone interest also consider taking a look at RESTful android this might give you a better look about it.

What i learned from the experience on trying to implement the Dobjanschi Model, is that not everything is written in stone and he only give you the overview of what to do this might changed from app to app but the formula is:

Follow this ideas + Add your own = Happy Android application

The model on some apps may vary from requirement some might not need the Account for the SyncAdapter other might use C2DM, this one that i worked recently might help someone:


Create an application that have Account and AccountManager

It will allow you to use the SyncAdapter to synchronized your data. This have been discussed on Create your own SyncAdapter

Create a ContentProvider (if it suits your needs)

This abstraction allows you to not only access the database but goes to the ServiceHelper to execute REST calls as it has one-per-one Mapping method with the REST Arch.

Content Provider | REST Method

query ----------------> GET

insert ----------------> PUT

update ----------------> POST

delete ----------------> DELETE

ServiceHelper Layering

This guy will basicly start (a) service(s) that execute a Http(not necessarily the protocol but it's the most common) REST method with the parameters that you passed from the ContentProvider. I passed the match integer that is gotten from the UriMatcher on the content Provider so i know what REST resource to access, i.e.

class ServiceHelper{

    public static void execute(Context context,int match,String parameters){
//find the service resource (/path/to/remote/service with the match
//start service with parameters 
    }

}

The service

Gets executed (I use IntentService most of the time) and it goes to the RESTMethod with the params passed from the helper, what is it good for? well remember Service are good to run things in background.

Also implement a BroadCastReceiver so when the service is done with its work notify my Activity that registered this Broadcast and requery again. I believe this last step is not on Virgill Conference but I'm pretty sure is a good way to go.

RESTMethod class

Takes the parameters, the WS resource(http://myservice.com/service/path) adds the parameters,prepared everything, execute the call, and save the response.

If the authtoken is needed you can requested from the AccountManager If the calling of the service failed because authentication, you can invalidate the authtoken and reauth to get a new token.

Finally the RESTMethod gives me either a XML or JSON no matter i create a processor based on the matcher and pass the response.

The processor

It's in charged of parsing the response and insert it locally.

A Sample Application? Of course!

Also if you are interesting on a test application you look at Eli-G, it might not be the best example but it follow the Service REST approach, it is built with ServiceHelper, Processor, ContentProvider, Loader, and Broadcast.

Solution 2

Programming Android has a complete chapter (13. Exploring Content Providers) dedicated to 'Option B: Use the ContentProvider API' from Virgil's Google I/O talk.

We are not the only ones who see the benefits of this approach. At the Google I/O conference in May 2010, Virgil Dobjanschi of Google presented a talk that outlined the following three patterns for using content providers to integrate RESTful web services into Android applications...

In this chapter, we’ll explore the second pattern in detail with our second Finch video example; this strategy will yield a number of important benefits for your applications. Due to the elegance with which this approach integrates network operations into Android MVC, we’ve given it the moniker “Network MVC.”

A future edition of Programming Android may address the other two approaches, as well as document more details of this Google presentation. After you finish reading this chapter, we suggest that you view Google’s talk.

Highly recommended.

Programming Android by Zigurd Mednieks, Laird Dornin, G. Blake Meike, and Masumi Nakamura. Copyright 2011 O’Reilly Media, Inc., 978-1-449-38969-7.

Solution 3

"Developing Android REST client applications" by Virgil Dobjanschi led to much discussion, since no source code was presented during the session or was provided afterwards.

  • A reference implementation is available under http://datadroid.foxykeep.com (the Google IO session is mentioned under /presentation). It is a library which you can use in your own application.
  • Android Priority Job Queue was inspired by Dobjanschi's talk and sounds very promising to me.

Please comment if you know more implementations.

Solution 4

We have developped a library that adresses this issue : RoboSpice.

The library uses the "service approach" described by Virgil Dobjanschi and Neil Goodmann, but we offer a complete all-in-one solution that :

  • executes asynchronously (in a background AndroidService) network requests that will return POJOs (ex: REST requests)
  • caches results (in Json, or Xml, or flat text files, or binary files)
  • notifies your activities (or any other context) of the result of the network request if they are still alive
  • doesn't notify your activities of the result if they are not alive anymore
  • notifies your activities on their UI Thread
  • uses a simple but robust exception handling model
  • supports multiple ContentServices to aggregate different web services results
  • supports multi-threading of request executions
  • is strongly typed !
  • is open source ;)
  • and tested

We are actually looking for feedback from the community.

Solution 5

Retrofit could be very helpful here, it builds an Adapter for you from a very simple configuration like:

Retrofit turns your REST API into a Java interface.

public interface GitHubService {
  @GET("/users/{user}/repos")
  List<Repo> listRepos(@Path("user") String user);
}

The RestAdapter class generates an implementation of the GitHubService interface.

RestAdapter restAdapter = new RestAdapter.Builder()
    .setEndpoint("https://api.github.com")
    .build();

GitHubService service = restAdapter.create(GitHubService.class); Each call on the generated GitHubService makes an HTTP request to the remote webserver.

List<Repo> repos = service.listRepos("octocat");

for more information visit the official site: http://square.github.io/retrofit/

Note: the adapter RestAdapter you get from Retrofit is not derived from BaseAdapter you should make a wrapper for it somehow like this SO question Why is my ListView empty after calling setListAdapter inside ListFragment?

Share:
39,242

Related videos on Youtube

FrVaBe
Author by

FrVaBe

Softwaredevelopment Java

Updated on July 05, 2022

Comments

  • FrVaBe
    FrVaBe about 2 years

    I want to build a REST Client on an android phone.

    The REST server exposes several resources, e.g. (GET)

    http://foo.bar/customer      List of all customer
    http://foo.bar/customer/4711    The customer with id 4711
    http://foo.bar/customer/vip     List of all VIP customer
    
    http://foo.bar/company           List of all companys
    http://foo.bar/company/4711     The company with the ID 4711
    http://foo.bar/company/vip      List of all VIP companys
    

    I (think) I know how to talk to the REST server and get the information I need. I would implement a REST Client class with an API like this

    public List<Customer> getCustomers();
    public Customer getCustomer(final String id);
    public List<Customer> getVipCustomer();
    
    public List<Company> getCompanies();
    public Customer getCompany(final String id);
    public List<Customer> getVipCompanies();
    

    Referred to the presentation "Developing Android REST client applications" from Virgil Dobjanschi I learned that it is no good idea to handle the REST request in an Worker Thread of the Activity. Instead I should use the Service API.

    I like the idea of having a Singleton ServiceHelper which binds to a (Local) Service but I am afraid that I did not understand the Service concept correct.

    For now I do not understand how to report a REST call result (done asynchrounous in a Service) back to the caller Activity. I also wonder if I need ONE Service which handles all REST requests (with different return types) or if I need a dedicated service for each REST request.

    Probably I have many other understanding problems so the best thing for me would be a sample application which meets my needs. My use case is not unusual and I hope there is in example application out there.

    Would you please let me know!

    Any other suggestions which points me in the correct implementation direction are also helpful (Android API-Demo does not match my use case).

    Thanks in advance.

    Klaus

    EDIT: Similar Topics found on SO (after posting this) which lead me in the direction I need (minimizing the complex "Dobjanschi pattern"):

    • Admin
      Admin almost 13 years
      Claszen, Did you get any opinion of single service for all request vs dedicated services for each request? If yes can you please share. Scenario in my case: I have many REST requests [around 20] to be used in my app. I have watched the valuable session in Google I/O mentioned above. My question is, which is the better approach. To have single service handling all the requests in single service? or to have a dedicated service for each of the requests? I have some of the requests that should be fired sequentially and some of them can be fired simultaneously. Any suggestions ?
    • FrVaBe
      FrVaBe over 12 years
      @user778869 I finally used one IntentService and ResultReceiver for each ('top level') REST resource (like 'company', 'customer'). I found this is a kind of 'natural' structure and works well. It may produced some code duplications but prevents from too heavy use of control structures if it were done all in one service.
    • Kay Zed
      Kay Zed over 10 years
      This might be very helpful for people learning Android REST client implementation. Dobjanschi's presentation transcribed into a PDF: drive.google.com/file/d/0B2dn_3573C3RdlVpU2JBWXdSb3c/…
  • FrVaBe
    FrVaBe over 13 years
    +1 Not really my use case but in any case a good and helpful Android application example. Thanks!
  • FrVaBe
    FrVaBe over 12 years
    Thanks for your answer. I finally used one IntentService and ResultReceiver for each ('top level') REST resource (like 'company', 'customer'). The Dobjanschi model was much too heavy for me.
  • Necronet
    Necronet over 12 years
    well b using IntentService and a ResultReseiver you probably using the first describe scenario which is a Service-Driven model, although he uses Binder instead of ResultReceiver for communication but that's good as I said is not written in stone!.
  • FrVaBe
    FrVaBe over 12 years
    Thanks for sharing this probably useful link (do not have the chance to take a deeper look at the moment)
  • FrVaBe
    FrVaBe almost 12 years
    It is some time ago that I asked the question and I found a solution that fitted for me. I did not have the possibility to check all the references to sample applications - but as this is the top most updated answer I will accept it. Nevertheless I recommend checking all other answers too.
  • Necronet
    Necronet almost 12 years
    Excelent sugestion, check all answer, all of them have a lot of good resources and ideas!! like Jeremy with the Programming Android book Yoni with the iosched source.
  • Vincent Cantin
    Vincent Cantin almost 12 years
    That looks like a solution. Thank you !
  • vaiomike
    vaiomike almost 12 years
    @Necronet hi there, just stumbled over your promising sample app - however, I'm having troubles building it. Would you mind telling us which version of ActionBarSherlock it has to be built against (seems it doesn't work w/ the latest ABS 4.1)? Also, from your post I did not really find out which pattern (A, B or C) of Dobjanschi's models you were aiming for (I know, you probably ended up w/ some variations, but I suppose you were mainly focusing on one of the patterns - I suppose pattern B?) Thanks!
  • Necronet
    Necronet almost 12 years
    Is quite an old project that I have not follow, I used ABS 2.x, and you are right pattern B that uses a ContentProvider + Services with Broadcast receiver that notify activity to reload the data.
  • exequielc
    exequielc almost 8 years
    Can you post a full example calling a rest service like api.icndb.com/jokes/random