How To get data from API in android studio tutorials -
Step 1 - Create Android Projects in Android Studio
Step 2 - Add internet Permission in Manifest file
<uses-permission android:name="android.permission.INTERNET"/>
Step 3 - Add Retrofit Library dependencies in build.gradle file for get response from API
and converte json file
and converte json file
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation'com.squareup.retrofit2:retrofit:2.9.0'
Step 4 -Create a Model class DataModel.java to call Api Response
public class DataModel {
}
Step 5 - Create a class RetrofitInstance.java
public class RetrofitInstance {
// STATIC INSTANCE FOR CALL ANYWHERE WITHOUT MAKE OBJECT
private static Retrofit retrofit;
// DEFINE YOUR BASE URL WHICH IS COMMON IN YOUR API
private static String BASE_URL = "https://jsonplaceholder.typicode.com/";
// CRETE A GETTER METHOD TO GET INSTANCE
public static Retrofit getRetrofit() {
// CONDITION FOR CREATE RETROFIT OBJECT
if (retrofit==null){
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create()).build();
}
return retrofit;
}
}
Step 6- Create a new interface Class ApiInterfaceEndPoint.java for ends points
public interface ApiInterfaceEndPoint {
@GET("todos")
Call<List<DataModel>> getData();
}
Step 7 - Call Data from API in Your in Activity
Before onCreate Method Create Retrofit instance
ApiInterfaceEndPoint apiInterface;
After Create Instance Write Code In onCreate method
apiInterface = RetrofitInstance.getRetrofit().create(ApiInterfaceEndPoint.class);
apiInterface.getData().enqueue(new Callback<List<DataModel>>() {
@Override
public void onResponse(Call<List<DataModel>> call, Response<List<DataModel>> response) {
if (response.body().size()>0){
Toast.makeText(MainActivity.this, "List is not Empty", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(MainActivity.this, "List is Empty", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<List<DataModel>> call, Throwable t) {
Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();
Log.d("error",t.getMessage());
}
});
Medium guide - link
API Making Tutorials - link
Implementation guide - link
Tags:
Android Development