Simple Android REST Service
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

I need really really generic and basic code for an Android app which connects to a RESTful API.

Given that I have an activity setup with three EditText fields, I need code for a service that will (a) save the field data in preferences (b) POST the data to a server and (c) save the result (temporarily in an ArrayList or another mechanism). Also, I need code which I can use to call this service from another activity.

More Detail

The Service part will have two requests (assign methods for each one):

  1. GET serverURL + "/get_request"
  2. POST serverURL + "/post_request"

The first request is a simple GET and will store the resulting data in an Array/ArrayList. The second request, which will be called with three strings (from the EditText fields), will call a POST the data, and like the first request, will store the resulting data in an Array/List.

Also, please create methods which would allow me to save the text field values in preferences (and also retrieve them later).

Here's what's provided/other stuff you should know:

  1. the server URL
  2. don't worry about text validation

The code needs to be able to easily extended to support me passing more data to the get/post and save/retieve methods.

awarded to andijcr

Crowdsource coding tasks.

1 Solution

Winning solution

I used Retrofit to generate the Rest client. just download the jar and put it in the libs folder

package yo.ma.ma;

import java.util.ArrayList;

import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.RestAdapter.LogLevel;
import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.http.Field;
import retrofit.http.FormUrlEncoded;
import retrofit.http.GET;
import retrofit.http.POST;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.IBinder;
import android.preference.PreferenceManager;

public class AsyncRestService extends Service {

    public interface RestClient {
        @GET("/getRequest")
        void asyncGetArrayList(Callback<ArrayList<String>> response);

        @FormUrlEncoded
        @POST("/postRequest")
        void asyncPostData(@Field("first") String field_1,
                @Field("second") String field_2,
                @Field("third") String field_3, Callback<String> callback);
    }

    public interface RestCallback {
        void onGetArrayList(ArrayList<String> result); //on Failure result is null
        void onPostDataResult(String result); //on Failure result is null
    }

    public class RestBinder extends Binder {
        AsyncRestService getService() {
            return AsyncRestService.this;
        }
    }

    private IBinder mBinder = new RestBinder();
    private RestClient mRest;
    private String server = "http:// >_< .com";
    private RestCallback callback;

    @Override
    public IBinder onBind(Intent arg0) {
        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        if (mRest == null) {
            mRest = new RestAdapter.Builder().setServer(server)
                    .setLogLevel(LogLevel.HEADERS).build()
                    .create(RestClient.class);
        }
    }

    // /RestMethods
    public void setCallback(RestCallback c) {
        callback = c;
    }

    public void unsetCallback() {
        callback = null;
    }

    public void getData() {
        mRest.asyncGetArrayList(new Callback<ArrayList<String>>() {
            RestCallback c = AsyncRestService.this.callback;

            @Override
            public void failure(RetrofitError arg0) {
                c.onGetArrayList(null);
            }

            @Override
            public void success(ArrayList<String> result, Response arg1) {
                c.onGetArrayList(result);
            }
        });
    }

    public void postData(String one, String two, String three) {
        mRest.asyncPostData(one, two, three, new Callback<String>() {
            RestCallback c = AsyncRestService.this.callback;

            @Override
            public void failure(RetrofitError arg0) {
                c.onPostDataResult(null);
            }

            @Override
            public void success(String result, Response arg1) {
                c.onPostDataResult(result);
            }
        });

    }

    public void persistThis(String one, String two, String three) {
        SharedPreferences settings = PreferenceManager
                .getDefaultSharedPreferences(this);
        settings.edit().putString("one", one).putString("two", two)
        .putString("three", three).commit();
    }

    public String[] retrieveThose() {
        String[] result = new String[3];
        SharedPreferences settings = PreferenceManager
                .getDefaultSharedPreferences(this);
        result[0] = settings.getString("one", null);
        result[1] = settings.getString("two", null);
        result[2] = settings.getString("three", null);

        return result;
    }
}

to use it, in your Activity: bind to it, pass it a RestCallback (tipically your activity) to receive results (setCallback), call getData() to init the get rest call, call postData(String one, String two, String three) to init the post rest call, call persistThis/restoreThose to persist/restore three strings. remember to call unsetCallback at the end of your activity lifecycle to prevent memoryleaks. the server instance variable holds the server URL

@andijcr is there anything I need to setup to use the Shared Preferences (for example, do I have to list it in the manifest) or can I just build and run?
sudo rm -rf / almost 6 years ago
@nacal build and run. i forgot to add that retrofit has a dependency on gson http://code.google.com/p/google-gson/ just grab the release zip and put it in the libs folder
andijcr almost 6 years ago