0

We have used a Activity-BL-DAO-DB(sqlite) in my app while developing.

Due to change in requirement, we have to use REST service from the server alone. I have seen Retrofit for it. But I'm not sure how to use it in DAO classes instead of SQL queries.

We have looked into bus concepts which requires more rework. We wanted to make minimal changes to the code to incorporate this change.

If anything else needed,let me know.

Eg: Following is the sample flow which will display list of technologies in the list.

Technology Activity OnCreate method:

    techList=new ArrayList<Technology>();
    techList=technologyBL.getAllTechnology(appId);
    adapterTech=new TechnologyAdapter(this,new ArrayList<Technology>  (techList));
    listView.setAdapter(adapterTech);

Technology BL :

    public List<Technology> getAllTechnology(String appId) {
        techList=technologyDao.getAllTechnology(appId);
        // some logic 
        return techList;
    }

Technology DAO:

    public List<Technology> getAllTechnology(String appId) {
        //sql queries
        return techList;
    }

Technology Model:

   class Technology{
        String id,techName,techDescription;
       //getters & setters
   }

I have to replace sql queries with retrofit request. I have created the following retrofit class and interfaces:

RestClient Interface:

    public interface IRestClient {

      @GET("/apps/{id}/technologies")
      void getTechnoloies(@Path("id") String id,Callback<List<Technology>> cb);

      //Remaining methods
    }

RestClient :

    public class RestClient {

          private static IRestClient REST_CLIENT;
          public static final String BASE_URL = "http://16.180.48.236:22197/api";
          Context context;

          static {
             setupRestClient();
          }

          private RestClient() {}

          public static RestClient get() {
             return REST_CLIENT;
          }

          private static void setupRestClient() {
               RestAdapter restAdapter = new RestAdapter.Builder()
                  .setEndpoint(BASE_URL)
                  .setClient(getClient())
                  .setRequestInterceptor(new RequestInterceptor() {
                  //cache related things
               })
               .setLogLevel(RestAdapter.LogLevel.FULL)
               .build();

               REST_CLIENT = restAdapter.create(IAluWikiClient.class);
           }

           private static OkClient getClient(){
                 //cache related
           }
    }

I tried calling with both sync/async methods in DAO. For sync method,it was throwing some error related to main thread.For Async,it is crashing as request is done late.

Sync call in DAO:

    techList=RestClient.get().getTecchnologies(id);

Async call in DAO:

    RestClient.get().getTechnolgies(id,new CallBack<List<Technolgy>(){
       @Override
       public void success(List<Technology> technologies, Response response)   {
            techList=technologies;
       }

       @Override
       public void failure(Retrofit error){}
   });
HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47
  • I am a little confused with what you are asking. Do you want to replace SQL queries with Retrofit? Using a RetrofitAdapter outside of an Activity should be simple to do. It might be good to post a little bit of your existing code and expound on what you are trying to update with it. – Andrea Thacker Aug 26 '15 at 17:35
  • yes. I want to replace sql queries with retrofit call. I have added code flow. Hope it helps. :) – Thayumaanavan CR Aug 27 '15 at 02:03

2 Answers2

2

You've got two options here.

The first is to create the Retrofit callback in the Activity:

RestClient.get().getTechnolgies(id,new CallBack<List<Technolgy>(){
   @Override
   public void success(List<Technology> technologies, Response response) {
        ArrayList<Technology> techList = technologyBL.someLogic(technologies);
        adapterTech=new TechnologyAdapter(this,techList);
        listView.setAdapter(adapterTech);
   }

   @Override
   public void failure(Retrofit error){}
});

Note that you will have to extract your //some logic part into a separate BL method.

The second option is to make the Retrofit API call return an RxJava Observable (which is integrated into Retrofit):

RestClient.get().getTechnolgies(id)
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Action1<List<Technology>>() {
         @Override
            public void call(List<Technology> technologies) {
                ArrayList<Technology> techList = technologyBL.someLogic(technologies);
                adapterTech=new TechnologyAdapter(this,techList);
                listView.setAdapter(adapterTech);
            }
     });

In this case, your RestClient interface is:

public interface IRestClient {

  @GET("/apps/{id}/technologies")
  Observable<List<Technology>> getTechnologies(@Path("id") String id);

  //Remaining methods
}

You can read more about it in the "SYNCHRONOUS VS. ASYNCHRONOUS VS. OBSERVABLE" section of http://square.github.io/retrofit/. Also, see these two blogposts to get your head around RxJava and Observables:

Alin Pandichi
  • 955
  • 5
  • 15
  • Thank you. By following this tutorial [ MVP & retrofit ](https://kmangutov.wordpress.com/2015/03/28/android-mvp-consuming-restful-apis/ ) and your code,I added Presenter class in between view and BL. It works now with async call. Now I want to know which is preferable Retrofit async method or RxJava method? – Thayumaanavan CR Aug 28 '15 at 13:53
  • I think that question is better answered here: [When should one use RxJava Observable and when simple Callback on Android?](http://stackoverflow.com/questions/21890338/when-should-one-use-rxjava-observable-and-when-simple-callback-on-android) – Alin Pandichi Aug 28 '15 at 14:02
  • Thank you.I think retrofit async will do the job for me as most of the calls are simple one. – Thayumaanavan CR Aug 28 '15 at 14:42
-2

In my experience, I have found it useful to create a Service which executes calls to the Retrofit API by using custom AsyncTask implementations. This paradigm keeps all your data model interactions in one place (the service) and gets all the API calls off the main thread.

zerobandwidth
  • 1,213
  • 11
  • 18