In continuation to the previous tutorial Android Post Data Using Retrofit Fetch Data Using Retrofit Library we will be fetching data using same retrofit library. Retrofit library is considered to be the fastest library so we will be using it.
Now in this tutorial on Android Fetch Data Using Retrofit Library we will be fetching data that we have posted previously refer the previous tutorial to get more info.
Let’s get started
Android Fetch Data Using Retrofit Library
Add Retrofit to your project please have a look at latest dependency’s version while adding them to your project to avoid deprecated code files may result in abnormal crashes.
Build.Gradle(Module:App)
dependencies { implementation 'com.squareup.retrofit2:converter-gson:2.2.0' implementation 'com.squareup.retrofit2:retrofit:2.3.0' }
activity_main.xml
Add four fields to display the values which are fetched from api provided
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="20dp" tools:context="retrieve.android.com.retrievedatausingretrofit.MainActivity"> <TextView android:id="@+id/nametxt" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="20dp" android:hint="Name"/> <TextView android:id="@+id/agetxt" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="20dp" android:hint="Age"/> <TextView android:id="@+id/phonetxt" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="20dp" android:hint="Phone"/> <TextView android:id="@+id/emailtxt" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="20dp" android:hint="Email"/> <Button android:id="@+id/retrieveBtn" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="40dp" android:text="Retrieve Data"/> </LinearLayout>
Api.java
Create a api file and specify the path here, also configure your Pojo file with it.
**GET parameter to fetch data
**POST parameter to post data
And these are configured with their respective model class files to fetch the response and parse them to make the data in java objects which an be directly used later.
import java.util.List; import retrofit2.Call; import retrofit2.http.GET; /** * Created by Android on 1/6/2018. */ public interface Api { String BASE_URL = "http://10.0.2.2/Data/"; @GET("fetch_data.php") Call<List<Details_Pojo>> getstatus(); }
Details_Pojo.java
And now here come Pojo file which is used to serialize and de serialize the variables.
package retrieve.android.com.retrievedatausingretrofit; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; /** * Created by Android on 1/6/2018. */ public class Details_Pojo { @SerializedName("Name") @Expose private String Name; @SerializedName("Age") @Expose private String Age; @SerializedName("Phone") @Expose private String Phone; @SerializedName("Email") @Expose private String Email; public String getName() { return Name; } public void setName(String name) { Name = name; } public String getAge() { return Age; } public void setAge(String age) { Age = age; } public String getPhone() { return Phone; } public void setPhone(String phone) { Phone = phone; } public String getEmail() { return Email; } public void setEmail(String email) { Email = email; } }
MainActivity.java
Using a Retrofit builder Fetch Data Using Retrofit Library
Retrofit retrofit = new Retrofit.Builder() .baseUrl(Api.BASE_URL) // Specify your api here .addConverterFactory(GsonConverterFactory.create()) .build();
Initialize api class
Api api = retrofit.create(Api.class);
Fetching the values into Pojo file
Call<List<Details_Pojo>> call = api.getstatus();
Now Fetch Data Using Retrofit Library on success and on failure conditions are specified here… on Success we are storing the response to our model class file and on Failure we are showing the reason for the failure
call.enqueue(new Callback<List<Details_Pojo>>() { @Override public void onResponse(Call<List<Details_Pojo>> call, Response<List<Details_Pojo>> response) { List<Details_Pojo> adslist = response.body(); // If Success using adslist fetch data here.... } @Override public void onFailure(Call<List<Details_Pojo>> call, Throwable t) { // Display your failure message here } });
After getting succeeded set the values to fields as you wish as of example i am making it in simple way
@Override public void onResponse(Call<List<Details_Pojo>> call, Response<List<Details_Pojo>> response) { List<Details_Pojo> adslist = response.body(); String name = adslist.get(0).getName(); String age = adslist.get(0).getAge(); String phone = adslist.get(0).getPhone(); String email = adslist.get(0).getEmail(); nametxt.setText(name); agetxt.setText(age); phonetxt.setText(phone); emailtxt.setText(email); }
If the call results in failure i am displaying a toast
@Override public void onFailure(Call<List<Details_Pojo>> call, Throwable t) { Toast.makeText(MainActivity.this, ""+t.getMessage().toString(), Toast.LENGTH_SHORT).show(); } });
Full code :
Providing full code for Fetch Data Using Retrofit Library
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class MainActivity extends AppCompatActivity { TextView nametxt, agetxt, phonetxt, emailtxt; Button retrieveBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); nametxt = (TextView) findViewById(R.id.nametxt); agetxt = (TextView) findViewById(R.id.agetxt); phonetxt = (TextView) findViewById(R.id.phonetxt); emailtxt = (TextView) findViewById(R.id.emailtxt); retrieveBtn = (Button) findViewById(R.id.retrieveBtn); retrieveBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { fetchData(); } }); } private void fetchData() { Retrofit retrofit = new Retrofit.Builder() .baseUrl(Api.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); Api api = retrofit.create(Api.class); Call<List<Details_Pojo>> call = api.getstatus(); call.enqueue(new Callback<List<Details_Pojo>>() { @Override public void onResponse(Call<List<Details_Pojo>> call, Response<List<Details_Pojo>> response) { List<Details_Pojo> adslist = response.body(); String name = adslist.get(0).getName(); String age = adslist.get(0).getAge(); String phone = adslist.get(0).getPhone(); String email = adslist.get(0).getEmail(); nametxt.setText(name); agetxt.setText(age); phonetxt.setText(phone); emailtxt.setText(email); } @Override public void onFailure(Call<List<Details_Pojo>> call, Throwable t) { Toast.makeText(MainActivity.this, ""+t.getMessage().toString(), Toast.LENGTH_SHORT).show(); } }); } }
ManifestActivity.xml
Mention INTERNET and ACCESS_NETWORK_STATE here to Fetch Data Using Retrofit Library
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="retrieve.android.com.retrievedatausingretrofit"> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Output :
The final view for Android Fetch Data Using Retrofit Library is depicted in the screens below. For more on retrofit tutorials may visit
If you are having any query’s in this tutorial on Fetch Data Using Retrofit Library do let us know in the comment section below. If you like this tutorial do like and share us for more interesting updates.