Wednesday, 27 April 2016

APIs with Retrofit

Retrofit library is created by Square Open Source, it’s a REST client for android and java. By the use of this library it is easy to request webservices of REST with GET, POST, PUT and many more.

Adding Libraries in Android Studio

1) Retrofit  :

   dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.squareup.retrofit:retrofit:1.9.0'
    compile 'com.squareup.okhttp:okhttp:2.4.0'

}

2)Add Permission:
 <uses-permission android:name="android.permission.INTERNET"/>

Code:

 private String url="http://services.hanselandpetal.com";


 final RestAdapter adapter = new RestAdapter.Builder().setEndpoint(url).build();
        RetrofitInterface api = adapter.create(RetrofitInterface.class);
        api.getData(new Callback<List<Model>>() {
            @Override
            public void success(List<Model> list, Response response) {
                progress.dismiss();
                myadapter=new MyAdapter(getApplicationContext(),list);
                list_View.setAdapter(myadapter);
            }

            @Override
            public void failure(RetrofitError error) {
                Log.d("Saravanana===>", "failure");
            }

        });

RetrofitInterface:

public interface RetrofitInterface {
    @GET("/feeds/flowers.json")
    public void getData(Callback<List<Model>> response);
}

Model:

public class Model implements Serializable {
    private static final long serialVersionUID = 1L;
    @SerializedName("name")
    public String name;
    @SerializedName("category")
    public String category;

}




To get Full Code Click Here

1 comment: