Wednesday 27 June 2018

How to use Retrofit to call an API in android. Full example to call any API using Retrofit rx in Android

In this Post i will tell you , how to make a network call in android to GET the data from api using Retrofit .

Do the following steps:-

1. First of all Open your android studio and go to File - New - New Project -Give the project name (whatever u wants i am giving - RetrofitExmp) and then click on - Next -Next -Next -Finish.

2. Now after opening your project click on (here project display mode is - android) app -java -click on your package (com.example.retrofitexmp).

3. Now right click on your app package -New - Package and give name ModelClass.

4. We r using this model class to parse the API data into is , so the model class structure should be match with the api  structure. For this we have to see the response. Here i am using one of the free api link for testing Link is :- https://jsonplaceholder.typicode.com/albums

Note:- before calling Retrofit we needs to add some packages to our app gradle:
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:27.1.1'
compile 'com.android.support.constraint:constraint-layout:1.1.2'
testImplementation 'junit:junit:4.12'
    // to use retrofit2 notation like @SerializedName("") @Expose    
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.3.0'
    // for the using of HttpLoggingInterceptor
compile 'com.squareup.okhttp3:okhttp:3.10.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.10.0'
    // For using AndroidSchedulers for io
compile 'io.reactivex:rxandroid:1.2.1'
compile 'io.reactivex:rxjava:1.3.4'}
5. Now click on ModelClass package and make a new java class with the name of GetAlbumListResponse.java. class will looks like following:-
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;

public class GetALbumListResponse implements Serializable{

    @SerializedName("userId")
    @Expose    
    public int userId;
    
    @SerializedName("id")
    @Expose    
    public int id;

    @SerializedName("title")
    @Expose    
    public String title;


}

6. Now for GET method call , I am creating a interface inside network package with the name of "AppInterface" code are following :-
import retrofit2.http.GET;
import retrofit2.http.Path;
import rx.Observable;

public interface AppInterface {

    @GET("{albums}")
    Observable<GetALbumListResponse> getAlbumListApi(@Path("albums") String albums);
}

7. Now for Retrofit Network call we have to create another class inside network package code are following  , as i made class (NetworkManager.java):-
public class NetworkManager {

    String url = "https://jsonplaceholder.typicode.com/";

    // make Retrofit network call with api link
    public AppInterface getRetrofitServices(Context context){

        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(httpLoggingInterceptor).build();
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();

        return retrofit.create(AppInterface.class);
    }
}

8. Now  we will call the api make separate class for this with the name of (AppApiControllerClass)code are following :-
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.schedulers.Schedulers;
import rx.android.schedulers.AndroidSchedulers;

public class AppApiControllerClass extends NetworkManager {

    public Subscription  getApiSubscription(final Context context, final OnHttpResponseListner listner) {

        final Observable<GetALbumListResponse> observable = getRetrofitServices(context).getAlbumListApi("albums");
        Subscription subscription = observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<GetALbumListResponse>() {
                    @Override                    
                    public void onCompleted() {}

                    @Override                    
                    public void onError(Throwable e) {
                    }
                    @Override                    
                    public void onNext(GetALbumListResponse response) {
                        listner.onSuccess(123,response);
                    }
                });
        return subscription;

    }
}
8. Now  in MainActivity.java class we will just call the method to his the api code are following :-
public class MainActivity extends AppCompatActivity implements OnHttpResponseListner{
    Subscription subscription;
    AppApiControllerClass appApiControllerClass;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //call api            appApiControllerClass = new AppApiControllerClass();
        appApiControllerClass.getApiSubscription(MainActivity.this, this);


    }

    @Override    public void onSuccess(int requestCode, GetALbumListResponse response) {
        Toast.makeText(MainActivity.this, response.toString(),Toast.LENGTH_LONG).show();

    }
}
9. Output :-







8 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.

    rpa training in Chennai | rpa training in pune

    rpa online training | rpa training in bangalore

    ReplyDelete
  3. Awesome article. It is so detailed and well formatted that i enjoyed reading it as well as get some new information too.
    java training in chennai | java training in bangalore

    java online training | java training in pune

    ReplyDelete
  4. Just stumbled across your blog and was instantly amazed with all the useful information that is on it. Great post, just what i was looking for and i am looking forward to reading your other posts soon!
    online Python certification course
    python training in OMR
    python training course in chennai

    ReplyDelete
  5. A very nice guide. I will definitely follow these tips. Thank you for sharing such detailed article. I am learning a lot from you.

    rpa training in electronic-city | rpa training in btm | rpa training in marathahalli | rpa training in pune

    ReplyDelete
  6. Thanks a lot for sharing us about this update. Hope you will not get tired on making posts as informative as this. 
    Best Devops Training in pune
    Devops Training in Chennai

    ReplyDelete