In the last android retrofit tutorial I explained how to retrieve JSON using HTTP GET request. In this android retrofit tutorial we will use post request.
So today we will insert some values from our android app to our MySQL Database.
In this tutorial I will be using Hostinger. Though you can use any hosting or local server (using wamp/xampp) as well.
So lets begin our android retrofit post request example. 🙂
Retrofit Android Tutorial – Using Retrofit 2.2 with PHP Restful API
Creating MySQL Database and PHP Scripts
- As I told that I am using Hostinger. And this is the snapshot of my database.

- This is my database, you should create the same database if you are going to copy my code. 😛
- Now we will create a script to connect to our database. I have created dbConnect.php.
1 2 3 4 5 6 7 8 9 10 11 | <?php //Change the values according to your database define('HOST','mysql.hostinger.in'); define('USER','u502452270_andro'); define('PASS','belal_123'); define('DB','u502452270_andro'); $con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect'); |
- Our second script will receive and insert the data to mysql database. I have created insert.php.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | <?php //checking if the script received a post request or not if($_SERVER['REQUEST_METHOD']=='POST'){ //Getting post data $name = $_POST['name']; $username = $_POST['username']; $password = $_POST['password']; $email = $_POST['email']; //checking if the received values are blank if($name == '' || $username == '' || $password == '' || $email == ''){ //giving a message to fill all values if the values are blank echo 'please fill all values'; }else{ //If the values are not blank //Connecting to our database by calling dbConnect script require_once('dbConnect.php'); //Creating an SQL Query to insert into database //Here you may need to change the retrofit_users because it is the table I created //if you have a different table write your table's name //This query is to check whether the username or email is already registered or not $sql = "SELECT * FROM retrofit_users WHERE username='$username' OR email='$email'"; //If variable check has some value from mysqli fetch array //That means username or email already exist $check = mysqli_fetch_array(mysqli_query($con,$sql)); //Checking check has some values or not if(isset($check)){ //If check has some value that means username already exist echo 'username or email already exist'; }else{ //If username is not already exist //Creating insert query $sql = "INSERT INTO retrofit_users (name,username,password,email) VALUES('$name','$username','$password','$email')"; //Trying to insert the values to db if(mysqli_query($con,$sql)){ //If inserted successfully echo 'successfully registered'; }else{ //In case any error occured echo 'oops! Please try again!'; } } //Closing the database connection mysqli_close($con); } }else{ echo 'error'; } |
- Now upload both files to your hosting. And notedown the URL for your insert.php file. In my case it is
http://simplifiedcoding.16mb.com/RetrofitExample/insert.php
Actually we are going to use retrofit So in retrofit we keep the root URL and the Main URL separately. In the above URL the unbold part is our root URL. We will understand it in our Android Project. Lets create an Android Studio Project.
Android Retrofit Tutorial
- Create a new Android Project. I have created project named RetrofitPostExample.
- Add the following dependency to build.gradle file.
1 2 3 | compile 'com.squareup.retrofit:retrofit:1.9.0' |
- Add internet permission to your manifest.
1 2 3 | <uses-permission android:name="android.permission.INTERNET"/> |
- Finally come to activity_main.xml. We have to create the following layout for this android retrofit tutorial.

- Use the following xml code for the above layout.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | <?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="user name" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <EditText android:id="@+id/editTextUsername" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:text="password" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <EditText android:id="@+id/editTextPassword" android:inputType="textPassword" 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:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> |
- Now come to MainActivity.java and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | //Class for our main activity with OnClickListener public class MainActivity extends AppCompatActivity implements View.OnClickListener { //Declaring views private EditText editTextName; private EditText editTextUsername; private EditText editTextPassword; private EditText editTextEmail; private Button buttonRegister; //This is our root url public static final String ROOT_URL = "http://simplifiedcoding.16mb.com/"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Initializing Views editTextName = (EditText) findViewById(R.id.editTextName); editTextUsername = (EditText) findViewById(R.id.editTextUsername); editTextPassword = (EditText) findViewById(R.id.editTextPassword); editTextEmail = (EditText) findViewById(R.id.editTextEmail); buttonRegister = (Button) findViewById(R.id.buttonRegister); //Adding listener to button buttonRegister.setOnClickListener(this); } private void insertUser(){ //Here we will handle the http request to insert user to mysql db } //Overriding onclick method @Override public void onClick(View v) { //Calling insertUser on button click insertUser(); } } |
- For retrofit we have to create an Interface. So create an Interface named RegisterAPI and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | package net.simplifiedcoding.retrofitpostexample; import retrofit.Callback; import retrofit.client.Response; import retrofit.http.Field; import retrofit.http.FormUrlEncoded; import retrofit.http.POST; /** * Created by Belal on 11/5/2015. */ public interface RegisterAPI { @FormUrlEncoded @POST("/RetrofitExample/insert.php") public void insertUser( @Field("name") String name, @Field("username") String username, @Field("password") String password, @Field("email") String email, Callback<Response> callback); } |
- So as you can see this is a common java interface. Inside it we are having
- @FormUrlEncoded, we have to write this if we want to send post data to the server.
- @POST, because we are using an HTTP Post request we have written this. Inside it we have the URL of the script that will be receiving the post request. Note that the URL is excluding the root URL. And we have defined the root URL in our MainActivity.
- public void insert() this is the method that will actually send the request. Inside this method we are having.
- @Field(“key”) String variable inside key we have to write what we have written inside $_POST[‘key’] in our script. And we have to specify it for all the values we are going to send.
- Callback<Response> callback it is also inside the retrofit library. It will receive the output from the server.
- But this is only an interface and the method is abstract. We will define the method inside insertUser() method that is declared inside MainActivity.java.
- So come to method insertUser() inside MainActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | private void insertUser(){ //Here we will handle the http request to insert user to mysql db //Creating a RestAdapter RestAdapter adapter = new RestAdapter.Builder() .setEndpoint(ROOT_URL) //Setting the Root URL .build(); //Finally building the adapter //Creating object for our interface RegisterAPI api = adapter.create(RegisterAPI.class); //Defining the method insertuser of our interface api.insertUser( //Passing the values by getting it from editTexts editTextName.getText().toString(), editTextUsername.getText().toString(), editTextPassword.getText().toString(), editTextEmail.getText().toString(), //Creating an anonymous callback new Callback<Response>() { @Override public void success(Response result, Response response) { //On success we will read the server's output using bufferedreader //Creating a bufferedreader object BufferedReader reader = null; //An string to store output from the server String output = ""; try { //Initializing buffered reader reader = new BufferedReader(new InputStreamReader(result.getBody().in())); //Reading the output in the string output = reader.readLine(); } catch (IOException e) { e.printStackTrace(); } //Displaying the output as a toast Toast.makeText(MainActivity.this, output, Toast.LENGTH_LONG).show(); } @Override public void failure(RetrofitError error) { //If any error occured displaying the error as toast Toast.makeText(MainActivity.this, error.toString(),Toast.LENGTH_LONG).show(); } } ); } |
- Now just run your application.

- And if you just got the success message as shown in the above image. Check your database.

- Bingo! It is working absolutely fine. If you are having troubles then you can download my php scripts and android project from below.
Get the Source Code of this Android Retrofit Tutorial
Here are few more tutorials for android application development you should check
- Android Retrofit Tutorial to Get JSON From Server
- Retrieve Data from MySQL Database using Volley Library
- Android Volley Tutorial to Create a Login Application
So thats all for this android retrofit tutorial guys. Feel free to ask anything regarding this android retrofit tutorial by your comments. And don’t forget to share this tutorial if you found it useful. Thank You 🙂

Hi, my name is Belal Khan and I am a Google Developers Expert (GDE) for Android. The passion of teaching made me create this blog. If you are an Android Developer, or you are learning about Android Development, then I can help you a lot with Simplified Coding.
Can php script handle 2,3 insert query? or we have to create another php file for different insert or query?
Yeah you can do both actually. You can handle 2,3 queries in the same php script and you can also create multiple scripts for handling multiple requests.. thats upto you
You can manage all the queries in the same php file, but It would be better to follow a pattern to make the maintaining sustainable.
Yeah agree with you.. following a pattern is essential otherwise you will be hitting your head against your desk when it will come to modify the existing code 😛
Hi i’m struggling to insert current time and date into SQL table. What type of date should I use? date, time, datetime, timestamp. I want to insert current time check in for an attendance app.
My logic is that php file will check SQL table whether user has checked in that day, if yes display message “already checked in” if no perform insert data with the current date and time
Any help is much appreciate,
Thanks in advance
I have wrote this code but did not work
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$staffID = $_POST['staffID'];
date_default_timezone_set("Asia/Singapore");
$checkInTime = $_SERVER['REQUEST_TIME'];
$today = date('Y-m-d');
require_once('dbconnect.php');
$sqlcheck = "SELECT * FROM StaffAttendacne WHERE StaffID = '$staffID' AND Date ='$today'";
$sql = "INSERT INTO StaffAttendance (StaffID,Date,CheckInTime) VALUES ('$staffID','$today','$checkInTime')";
$result = mysqli_query($con,$sqlcheck);
$check = mysqli_fetch_array($result);
if (isset($check)){
echo "You have already checked in";
}else {
echo"$checkInTime";
mysqli_query($con,$sql);
}
i get this error when register
retrofit.RetrofitError:
libcore.net.url.FtpURLConnection cannot be cast to java.net.HttpURLConnection
how to solve?
my root URL is ftp://….
you should use http not http://ftp.. ftp is a file transfer protocol thats why you are getting the exception
I can not able to download this application plz provide me any other link?
Hello
It is possible if you teach me how to insert a date(datepicker) or time (timepicker) into mysql database..Thxz
thank you
where is mysql db create that kind of sql code is missing
No need to write sql you can create db table by using some clicks in mysql .. So i left that part.. just go to your phpmyadmin and create a database like that.
Excellent tutorial thank you!
After a user has been succesfully registered it displays the toast “success” for example. After a user has registered i would like it to automatically switch to another activity ie the login screen.
I am unsure of how to do this.
If you could explain how to implement this, it would be very much appreciated
Thanks
we have upload both files to github so how can i know which part of the URL is root or main
can you please till which one which
https://github.com/RawanTK/ll/blob/master/Simple-Android-PHP-MYSQL–master/root-php/insert.php
Now if uploaded both files to my github
https://github.com/RawanTK/ll/blob/master/Simple-Android-PHP-MYSQL–master/root-php/insert.php
which one is the root part and which one is the main?
very good tutorial.. now I wonder how to add delete and update method.
Great post, may I know How Can I show Progress Dialog while storing data to database ?
Just to provide great experience to users
I need script code for confirm password , How to write this code and add it in PHP file ?
thank you
Great!
I’m a beginner with Android. But I like such full examples very much. Because I just start with Retrofit I would like to use release 2. I got a little app working with 1.9 , but there are a lot of changes in 2.
Do you intent to rewrite this example for 2.0?
The problem I have at this moment special is how to manage the method insetUser (http put)
A little help will be great. Thanks in advance. (I’m just programming for fun; I’m 71 years old..)
How to update and delete using retrofit?
Your Code don’t work. Cant’t use Inetrnet ressource in UI Thread.
Hello… What would happen when my app does not have internet connection and I try to insert the new data? Is possible to store this data set and when the app gets connection transfer to mysql?
good tutorial, can I use this tutorial to connect the database with sql server?
if i only have connection string of mysql database and not have any scripting on the server side then i can use retrofit to communicate with server
Truly, it is a good tutorial but I am facing a problem when I tried to insert the data into MySQL. It shows retrofitError protocol not found:~/insert.php
~ is my ip address..
Hopefully you can help me..
Hi…Thanks for your Tutorial
I am facing a problem when i click a Register Button” (HTTPLog)-Static: isSBSettingEnabled false error and app is closing”
Pls help me out
Will you do for Retrofit 2 ?
Yeah you will get it in upcoming posts.
Please Update Tutorial with Retrofit 2.0.
Hi Belal,thank you for nice tutorial.
I am implementing this in my application,but I can successfully insert data to database only once FOR THE FIRST TIME WHEN I LAUNCH IT.I have no idea what is the problem ,Is it that i have to clear everything after insertion?
Thank you and wait for feedback:)
Actually,i have noticed there is no problem with codes,but how to set timeout connection or making request proceed for certain time?
hii,
This code is running perfectly in emulator but when i run it from any device then something goes wrong i thing its because ip address of system. so tell me some solution how i come over from this problem .i tried hard
just replace localhost with your computer ip address and it should work fine.
I keep getting a toast that says retrofit.Retrofiterror: Connect Timed out
How do i fix this please help.
public interface RetrofitObjectAPI
{
@FormUrlEncoded
@POST(“senddata/index.php”)
public void insertData(
@Field(“DeviceID”) String UserID,
@Field(“DevicePassword”) String UserPassword,
Callback callback);
Call getDataDetail();
}
how to implement this in retrofit.., tq
Hi Belal,
I am trying to run it in localhost server WAMP.
I tried:
1. public static final String ROOT_URL = “http://localhost/o-dtr/”; – my root directory
ERROR: Retrofit error: connection refused
2. public static final String ROOT_URL = “http://192.168.165.###/o-dtr/”; – my IP address
ERROR: D/NetworkSecurityConfig: No Network Security Config specified, using platform default
My PHP and MySQL server is working fine.
Please guide me.. thanks.
Wil
how to add headers while sending request
Bro what we have to do if we wana add profile image too as a parameter. pls help
Showing Missing Method body or declare abstract in the RegisterAPI.java file. How to solve this issue plz help me.
Thanks & regards,
Thiru
i have error in toast
i am getting error in toast and data is not being inserted in database can you help me..
Followed the same tutorial….404 error it is showing.
how can i fetch data i had register to show information self
RestAdapter doesnt get resolved please help me out
can you help me, i want create login user how to get work ?