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:
6. Now for GET method call , I am creating a interface inside network package with the name of "AppInterface" code are following :-
7. Now for Retrofit Network call we have to create another class inside network package code are following , as i made class (NetworkManager.java):-
8. Now we will call the api make separate class for this with the name of (AppApiControllerClass)code are following :-
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 :-