Get Data and Post Data using Retrofit:2.1.0

Retrofit 2.1.0 in android, Retrofit demo, Retrofit example, get and post using Retrofit 2.1.0, Rest api using retrofit

  • Retrofit is use to make http calls on server, it is the best alternative of volley for client-server communication. 
  • Retrofit is a type-safe REST client design by Square for Android.
  • Using Retrofit developer can easily make network related stuff in speedy way.
  • Retrofit is using annotation for network transaction.
Here is the demo of how can we use Retrofit 2.1.0 library for GET and POST data to server.

STEP : 1


compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.google.code.gson:gson:2.7'

First integrate dependency in your build.gradle (Module:app) file for retrofit library as well gson converter library for parsing json data and sync project:



STEP : 2

START WITH GET REQUEST WITH RETROFIT 2.1.0

STEP : 3

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="18sp"
        android:text="Retrofit 2 Demo!"
        android:id="@+id/textView" />

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Load Data"
        android:id="@+id/button_get_data"
        android:onClick="loadData"
        android:background="#00b489"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:layout_below="@+id/textView"
        android:layout_toLeftOf="@+id/progressBar"
        android:layout_toStartOf="@+id/progressBar" />

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Post Data"
        android:id="@+id/button_post_data"
        android:onClick="onRedirect"
        android:background="#00b489"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:layout_above="@+id/recycle_view"
        android:layout_toRightOf="@+id/progressBar"
        android:layout_toEndOf="@+id/progressBar" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycle_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/button_get_data"
        android:layout_margin="10dp">

    </android.support.v7.widget.RecyclerView>

    <ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/progressBar"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:visibility="invisible" />
</RelativeLayout>


Now we create activity.xml file for MainActivity UI to get data from server and bind in recycleview.



STEP : 4

Create MainActivity.java





public class MainActivity extends AppCompatActivity {

    RecyclerView mRecyclerView;
    ProgressBar mProgressBar;
    public static final String ROOT_URL = "YOUR BASE URL HERE";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initUIControls();
        initClassObjects();
    }

    private void initUIControls() {
        mRecyclerView = (RecyclerView) findViewById(R.id.recycle_view);
        mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
    }

    private void initClassObjects() {

    }

    public void onRedirect(View view){
        startActivity(new Intent(this, RegistrationActivity.class));
    }
    public void loadData(View view) {

        mProgressBar.setVisibility(View.VISIBLE);

        Gson gson = new GsonBuilder()
                .create();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ROOT_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();

        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseData> call = responseApi.getResponse();
        call.enqueue(new Callback<ResponseData>() {
            @Override
            public void onResponse(Call<ResponseData> call, 
                                     Response<ResponseData> response) {
                Toast.makeText(MainActivity.this, "onResponse :: "+response.code(), 
                                                             Toast.LENGTH_SHORT).show();

                ResponseData responseData = response.body();

                List<Contact> list = responseData.getContacts();
                if (null != list && list.size() > 0) {

                    MyRecyclerAdapter myRecyclerAdapter = 
                                          new MyRecyclerAdapter(MainActivity.this, list);
                    mRecyclerView.setHasFixedSize(true);
                    mRecyclerView.setAdapter(myRecyclerAdapter);
                    mRecyclerView.setLayoutManager(new LinearLayoutManager
                                                                   (MainActivity.this));
                    mRecyclerView.setItemAnimator(new DefaultItemAnimator());

                } else {
                    Toast.makeText(MainActivity.this, "No records found!", 
                                                             Toast.LENGTH_SHORT).show();
                }
                mProgressBar.setVisibility(View.INVISIBLE);

            }

            @Override
            public void onFailure(Call<ResponseData> call, Throwable t) {
                t.printStackTrace();
                Toast.makeText(MainActivity.this, "onFailure", Toast.LENGTH_SHORT).show();
                mProgressBar.setVisibility(View.INVISIBLE);
            }
        });

    }
}

STEP : 5 
Create adapter MyRecyclerAdapter.java for Recycleview:


public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.ViewHolder> {

    List<Contact> result = null;
    Context mContext;

    public MyRecyclerAdapter(Context context, List<Contact> _result) {
        this.result = _result;
        this.mContext = context;
    }

    @Override
    public MyRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).
                                         inflate(R.layout.single_list_cell, parent, false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(MyRecyclerAdapter.ViewHolder holder, 
                                                                  final int position) {
        Contact item = result.get(position);

        holder.textName.setText(item.getName());
        holder.textEmail.setText(item.getEmail());
        holder.textMobile.setText(item.getPhone().getMobile());
    }

    @Override
    public int getItemCount() {
        return result.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public TextView textName;
        public TextView textEmail;
        public TextView textMobile;

        public ViewHolder(View itemView) {
            super(itemView);
            textName = (TextView) itemView.findViewById(R.id.text_name);
            textEmail = (TextView) itemView.findViewById(R.id.text_email);
            textMobile = (TextView) itemView.findViewById(R.id.text_mobile);

        }
    }

}

STEP : 6 
Create interface ResponseApi.java for api:

public interface ResponseApi {

    //Actual URL for GET :: http://YOUR BASE URL/contacts/
    
    @GET("/contacts")
    Call<ResponseData> getResponse();
}

STEP : 7 Create Modals classes for parsing json using gson.
Create ResponseData.java for GET request response

public class ResponseData {

//User @SerializedName("your Json data key") annotation for key from json data
    @SerializedName("contacts")
    @Expose
    public List<Contact> contacts;

    public List<Contact> getContacts() {
        return contacts;
    }

    public void setContacts(List<Contact> contacts) {
        this.contacts = contacts;
    }
}

Create Contact.java as Contact is one of the key data in our json

public class Contact {
    @SerializedName("name")
    @Expose
    public String name;

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

    @SerializedName("phone")
    @Expose
    public PhoneData phone;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public PhoneData getPhone() {
        return phone;
    }

    public void setPhone(PhoneData phone) {
        this.phone = phone;
    }
}

Create PhoneData.java as it is one of the key data in our json

public class PhoneData {

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

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
}

STEP : 8   Finally add permissions in AndroidMenifiest.xml file

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

 :: Result of GET Request ::


NOW WITH POST REQUEST WITH RETROFIT 2.1.0

STEP : 1

Create registration_view.xml for registration view for posting data to server with retrofit

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <TextView
        android:text="Name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <EditText
        android:id="@+id/editTextName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />


    <TextView
        android:text="Email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />


    <EditText
        android:id="@+id/editTextEmail"
        android:inputType="textEmailAddress"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/buttonRegister"
        android:text="Register"
        android:onClick="onPostData"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/text_view_result"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="20dp"
        android:visibility="invisible"
        android:gravity="center" />

</LinearLayout>

STEP : 2 

 Create RegistrationActivity.java for post data


public class RegistrationActivity extends AppCompatActivity {

    EditText editTextName,editTextEmail;
    TextView txtResponse;

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

        initUIControls();
    }

    private void initUIControls() {
        // get reference to the views
        editTextName = (EditText) findViewById(R.id.editTextName);
        editTextEmail = (EditText) findViewById(R.id.editTextEmail);
        txtResponse = (TextView) findViewById(R.id.text_view_result);

        // check if you are connected or not
        if(isConnected()){
            Toast.makeText(RegistrationActivity.this, "You are connected!", 
                                                           Toast.LENGTH_SHORT).show();
        }

    }

    public void onPostData(View view){

        if(!validate()){
            Toast.makeText(RegistrationActivity.this, "Some data missing!",
                                                         Toast.LENGTH_SHORT).show();
        }else {
            Toast.makeText(RegistrationActivity.this, "Sending...",
                                                         Toast.LENGTH_SHORT).show();


            String name = editTextName.getText().toString();
            String email = editTextEmail.getText().toString();

            Gson gson = new GsonBuilder()
                    .create();
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl("YOUR BASE URL HERE")
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();


            ResponseApi responseApi = retrofit.create(ResponseApi.class);
            Call<RegistrationResponse> call = responseApi.sendData(name, email);
            call.enqueue(new Callback<RegistrationResponse>() {
                @Override
                public void onResponse(Call<RegistrationResponse> call, 
                                          Response<RegistrationResponse> response) {
                    Toast.makeText(RegistrationActivity.this, 
                                   "Success :: "+response.code(),Toast.LENGTH_LONG).show();

                    if(response.code() == 200){
                        RegistrationResponse rr = response.body();
                        Log.v("Status", rr.getStatus());
                        txtResponse.setVisibility(View.VISIBLE);
                        txtResponse.setText(" :: You are registered As :: \n"+
                                                "Name : "+rr.getData().name+" \n "+
                                                "Email : "+rr.getData().email
                                            );

                    }
                }
                @Override
                public void onFailure(Call<RegistrationResponse> call, Throwable t) {
                    Toast.makeText(RegistrationActivity.this, t.getMessage(),
                                                            Toast.LENGTH_LONG).show();
                    txtResponse.setVisibility(View.VISIBLE);
                    txtResponse.setText(" :: Error :: \n"+
                                        t.getMessage()
                                        );
                }
            });

        }
    }

    public boolean isConnected(){
        ConnectivityManager connMgr = (ConnectivityManager) 
                                         getSystemService(Activity.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected())
            return true;
        else
            return false;
    }
    private boolean validate(){
        if(editTextName.getText().toString().trim().equals(""))
            return false;
        else if(editTextEmail.getText().toString().trim().equals(""))
            return false;
        else
            return true;
    }
}

STEP : 3 

 Now add one more method for post data in our existed ResponseApi.java interface


public interface ResponseApi {

    //Actual URL GET :: YOUR API BASE URL/contacts
    //Actual URL POST :: YOUR API BASE URL/webservice/testlogin

    @GET("/contacts")
    Call<ResponseData> getResponse();

    @FormUrlEncoded
    @POST("/webservice/testlogin")
    Call<RegistrationResponse> sendData(@Field("name") String name,
                                        @Field("email") String email);
}

STEP : 4   Create pojo class RegistrationResponse.java for registration response store


public class RegistrationResponse {

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

    public PostData getData() {
        return data;
    }

    public void setData(PostData data) {
        this.data = data;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    @SerializedName("data")
    @Expose
    public PostData data;
}

STEP : 5

Create another one pojo class as our json data response PostData.java



public class PostData {
    @SerializedName("name")
    @Expose
    public String name;
    @SerializedName("email")
    @Expose
    public String email;
}



 :: Result of POST Request ::



Check out the full demo here : https://github.com/CDL24/Retrofit-POST-Demo

Just download and import full android studio project.

And if you like my efforts please share the blog and hits like Happy Coding ;)

Comments