Android Retrofit Tutorial to Insert into MySQL Database

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

Creating MySQL Database and PHP Scripts

  • As I told that I am using Hostinger. And this is the snapshot of my database.
mysql db
mysql db
  • 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.

  • Our second script will receive and insert the data to mysql database. I have created insert.php.

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

  • Add internet permission to your manifest.

  • Finally come to activity_main.xml. We have to create the following layout for this android retrofit tutorial.
android retrofit tutorial
android retrofit tutorial
  • Use the following xml code for the above layout.

  • Now come to MainActivity.java and write the following code.

  • For retrofit we have to create an Interface. So create an Interface named RegisterAPI and write the following code.

  • 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

  • Now just run your application.
android retrofit tutorial
android retrofit tutorial
  • And if you just got the success message as shown in the above image. Check your database.
mysql db
mysql db
  • 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 

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 🙂

46 thoughts on “Android Retrofit Tutorial to Insert into MySQL Database”

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

    Reply
  2. 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

    Reply
  3. 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);
    }

    Reply
  4. 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://….

    Reply
  5. 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

    Reply
  6. 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..)

    Reply
  7. 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?

    Reply
  8. 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

    Reply
  9. 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..

    Reply
  10. 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

    Reply
  11. 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:)

    Reply
  12. 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

    Reply
  13. 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

    Reply
  14. 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

    Reply
  15. Showing Missing Method body or declare abstract in the RegisterAPI.java file. How to solve this issue plz help me.

    Thanks & regards,
    Thiru

    Reply

Leave a Comment