Android Tutorial on Retrofit Library || Post Data Using Retrofit Http Library

Android Retrofit :

Android retrofit, Communication between app and server is a much very important task which needs to be carefully handed using a fastest and much efficient library to make this process much easier for even the novice.

Almost every app needs to perform a server call that might be to exchange data for analytics upload / download images, data and many more.

Every app which deals with the network call has to perform background operations in order to make communication in between app and server to be possible.

Using retrofit we not only can upload data and images but also various files like pdf, gif and documents depending upon the user requirements using Multipart file upload.

In this Android Tutorial on Retrofit Library we will learn how to post data to server using this retrofit library.

 

We will be using a local server for this tutorial so if your are not aware of the local server usage and installation please refer below tutorials for any further.

 

https://androidcoding.in/2018/02/10/android-installation-local-server-local-host-wamp-server-installation/

 

Android retrofit

Add Retrofit to your project

build.gradle(Module:app)

Look for the latest dependency’s i.e., the version to avoid the usage of deprecated code which may result in abnormal crashes.

dependencies {
...........
    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.2.0'
    implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'
...........
}

 

activity_main.xml

Create a simple user interface to insert data using android retrofit, add required fields.

<?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="retrofit.android.com.insertdatausingretrofit.MainActivity">

    <EditText
        android:id="@+id/nametxt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="name"/>

    <EditText
        android:id="@+id/agetxt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="age"/>

    <EditText
        android:id="@+id/phonetxt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="phone"/>

    <EditText
        android:id="@+id/emailtxt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="email"/>

    <Button
        android:id="@+id/submitBtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:text="Submit"/>

</LinearLayout>

 

and then lets start coding further

 

ApiUtils.java

Create a utility file where you can add your api url.

 

public class ApiUtils {

    private ApiUtils() {}

    public static final String BASE_URL = "Your URL here";

    public static APIService getAPIService() {

        return RetrofitClient.getClient(BASE_URL).create(APIService.class);
    }
}

 

APIService.java

In service class mention your parameters i.e., our key values by using which you want to fetch values

 

import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;

public interface APIService {
    @FormUrlEncoded
    @POST("insert_data.php")
    Call<String> getStringScalar(@Field("name") String name, @Field("age")
            String age, @Field("phone") String phone, @Field("email") String email);

}

 

RetrofitClient.java

Configuring your retrofit client accordingly

 

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitClient {

    private static Retrofit retrofit = null;

    public static Retrofit getClient(String baseUrl) {

        Gson gson = new GsonBuilder().setLenient().create();

        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();
        }
        return retrofit;
    }
}

 

MainActivity.java

Initialize android retrofit service

private APIService mAPIService = ApiUtils.getAPIService();

Now for sending post request using retrofit

public void sendPost(String name, String age, String phone, String email) throws IOException {

    Call<String> call = mAPIService.getStringScalar(name, age, phone, email);

    call.enqueue(new Callback<String>() {
        @Override
        public void onResponse(Call<String> call, Response<String> response) {

            Toast.makeText(MainActivity.this, "Data Inserted Successfully", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailure(Call<String> call, Throwable t) {

            Toast.makeText(MainActivity.this, "Error" + t.getMessage().toString(), Toast.LENGTH_SHORT).show();

        }
    });

}

 

Full Code :

Providing full code for android retrofit usage.

 

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.IOException;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {

    EditText nametxt, agetxt, phonetxt, emailtxt;
    private APIService mAPIService;
    Button submitBtn;

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

        nametxt = (EditText) findViewById(R.id.nametxt);
        agetxt = (EditText) findViewById(R.id.agetxt);
        phonetxt = (EditText) findViewById(R.id.phonetxt);
        emailtxt = (EditText) findViewById(R.id.emailtxt);

        submitBtn = (Button) findViewById(R.id.submitBtn);

        mAPIService = ApiUtils.getAPIService();

        submitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                try {
                    sendPost(nametxt.getText().toString(), agetxt.getText().toString(), phonetxt.getText().toString(), emailtxt.getText().toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });

    }

    public void sendPost(String name, String age, String phone, String email) throws IOException {

        Call<String> call = mAPIService.getStringScalar(name, age, phone, email);

        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {

                Toast.makeText(MainActivity.this, "Data Inserted Successfully", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

                Toast.makeText(MainActivity.this, "Error" + t.getMessage().toString(), Toast.LENGTH_SHORT).show();

            }
        });

    }


}

 

AndroidManifest.xml

Provide internet permission for android retrofit usage

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="retrofit.android.com.insertdatausingretrofit">

    <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>

 

PHP Files

Visit this tutorial for creating php based api for this tutorial

https://androidcoding.in/2019/01/26/insert-into-php/

 

Output

The final view of Android Tutorial on Retrofit Library is shown in the screen for more info may visit

Android Tutorial on Retrofit Library

 

For any query’s in this tutorial on android retrofit do let us know in the comment section below or on instagram. If you like this tutorial do like and share for more interesting updates.

Show Buttons
Hide Buttons