Tuesday 13 June 2017

Simple Retrofit with GSON using GET method



STEP : 1 - Add below permistion to AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>

STEP : 2 - Add below library to App Level gradle file

  // retrofit, gson
    compile 'com.google.code.gson:gson:2.8.0'
    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.squareup.retrofit2:converter-gson:2.0.2'

STEP - 3 : Create 'ApiInterface.interface'  - This inteface send and receive response  to server using
GET method.

import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;

public interface ApiInterface {
    @GET("/json/movies.json")
    Call<List<Movie>> getTopRatedMovies();
}

Note : @GET("/json/movies.json") - It's call URL and get response using GET method. "/json/movies.json" is part of url because In Retrofit, we can't use full URL.
 Full URL - http://api.androidhive.info/json/movies.json ->

Call<List<Movie>> - This retrofit method that sends a request to a webserver and returns a response to a pojo class.

STEP - 4 :  ApiClient.class  - This class have Retrofit instance and parameter and conversion type.


import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiClient {
    public static final String BASE_URL = "http://api.androidhive.info";
    private static Retrofit retrofit = null;
    public static Retrofit getClient() {
        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

Note :  * Retrofit adapts a Java interface to HTTP calls by using annotations on the declared methods to
 * define how requests are made. Create instances using {@linkplain Builder
 * the builder} and pass your interface to {@link #create} to generate an implementation.
 * <p>
 * For example,
 * <pre><code>
 * Retrofit retrofit = new Retrofit.Builder()
 *     .baseUrl("https://api.example.com/")
 *     .addConverterFactory(GsonConverterFactory.create())
 *     .build();
 *
 * MyApi api = retrofit.create(MyApi.class);
 * Response&lt;User&gt; user = api.getUser().execute();

STEP - 5 : MainActivity.java

------------------------------------------------------------------------------------------***

import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.widget.Toast;import java.util.List;import retrofit2.Call;import retrofit2.Callback;import retrofit2.Response;
public class MainActivity extends AppCompatActivity {

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);
        ApiInterface apiService =
                ApiClient.getClient().create(ApiInterface.class);
        Call<List<Movie>> call = apiService.getTopRatedMovies();        call.enqueue(new Callback<List<Movie>>() {
            @Override            public void onResponse(Call<List<Movie>> call, Response<List<Movie>> response) {
                int statusCode = response.code();                List<Movie> movies = response.body();
                for(int i = 0; i<movies.size(); i++)
                {
                    String title = movies.get(i).getTitle();                    String image = movies.get(i).getImage();                    Double rating = movies.get(i).getRating();                    int release_year = movies.get(i).getReleaseYear();                    List<String> listGenre = movies.get(i).getGenre();                    String sumGenre = null;                    for(int j=0; j<listGenre.size(); j++)
                    {
                        String s = listGenre.get(j).toString();
                        sumGenre = sumGenre+", "+s;                    }

                    Toast.makeText(MainActivity.this, title+", "+image+", "+rating+", "+release_year+", "+sumGenre+", "+" : "+statusCode, Toast.LENGTH_SHORT).show();                }
                }

            @Override            public void onFailure(Call<List<Movie>> call, Throwable t) {
                // Log error here since request failed                Log.e("TAG", t.toString());            }
        });    }
}

NOTE : 
enqueue - /** * Asynchronously send the request and notify {@code callback} of its response 
or if an error * occurred talking to the server, creating the request, or processing the 
response. */
  
 Callback - * Communicates responses from a server or offline requests. One and only one 
method will be* invoked in response to a given request. 
------------------------------------------------------------------------------------------***

MOVIE JSON LIST
------------------------------------------------

[{
        "title": "Dawn of the Planet of the Apes",
        "image": "http://api.androidhive.info/json/movies/1.jpg",
        "rating": 8.3,
        "releaseYear": 2014,
        "genre": ["Action", "Drama", "Sci-Fi"]
    },
    {
        "title": "District 9",
        "image": "http://api.androidhive.info/json/movies/2.jpg",
        "rating": 8,
        "releaseYear": 2009,
        "genre": ["Action", "Sci-Fi", "Thriller"]
    },
    {
        "title": "Transformers: Age of Extinction",
        "image": "http://api.androidhive.info/json/movies/3.jpg",
        "rating": 6.3,
        "releaseYear": 2014,
        "genre": ["Action", "Adventure", "Sci-Fi"]
    },
    {
        "title": "X-Men: Days of Future Past",
        "image": "http://api.androidhive.info/json/movies/4.jpg",
        "rating": 8.4,
        "releaseYear": 2014,
        "genre": ["Action", "Sci-Fi", "Thriller"]
    },
    {
        "title": "The Machinist",
        "image": "http://api.androidhive.info/json/movies/5.jpg",
        "rating": 7.8,
        "releaseYear": 2004,
        "genre": ["Drama", "Thriller"]
    },
    {
        "title": "The Last Samurai",
        "image": "http://api.androidhive.info/json/movies/6.jpg",
        "rating": 7.7,
        "releaseYear": 2003,
        "genre": ["Action", "Drama", "History"]
    },
    {
        "title": "The Amazing Spider-Man 2",
        "image": "http://api.androidhive.info/json/movies/7.jpg",
        "rating": 7.3,
        "releaseYear": 2014,
        "genre": ["Action", "Adventure", "Fantasy"]
    },
    {
        "title": "Tangled",
        "image": "http://api.androidhive.info/json/movies/8.jpg",
        "rating": 7.9,
        "releaseYear": 2010,
        "genre": ["Action", "Drama", "Sci-Fi"]
    },
    {
        "title": "Rush",
        "image": "http://api.androidhive.info/json/movies/9.jpg",
        "rating": 8.3,
        "releaseYear": 2013,
        "genre": ["Animation", "Comedy", "Family"]
    },
    {
        "title": "Drag Me to Hell",
        "image": "http://api.androidhive.info/json/movies/10.jpg",
        "rating": 6.7,
        "releaseYear": 2009,
        "genre": ["Horror", "Thriller"]
    },
    {
        "title": "Despicable Me 2",
        "image": "http://api.androidhive.info/json/movies/11.jpg",
        "rating": 7.6,
        "releaseYear": 2013,
        "genre": ["Animation", "Comedy", "Family"]
    },
    {
        "title": "Kill Bill: Vol. 1",
        "image": "http://api.androidhive.info/json/movies/12.jpg",
        "rating": 8.2,
        "releaseYear": 2003,
        "genre": ["Action", "Crime"]
    },
    {
        "title": "A Bug's Life",
        "image": "http://api.androidhive.info/json/movies/13.jpg",
        "rating": 7.2,
        "releaseYear": 1998,
        "genre": ["Animation", "Adventure", "Comedy"]
    },
    {
        "title": "Life of Brian",
        "image": "http://api.androidhive.info/json/movies/14.jpg",
        "rating": 8.9,
        "releaseYear": 1972,
        "genre": ["Comedy"]
    },
    {
        "title": "How to Train Your Dragon",
        "image": "http://api.androidhive.info/json/movies/15.jpg",
        "rating": 8.2,
        "releaseYear": 2010,
        "genre": ["Animation", "Adventure", "Family"]
    }]
---------------------------------------------------------------------
















































































22

No comments:

Post a Comment