Simplified Coding

  • About
  • Contact Us
  • Advertise
  • Privacy Policy
You are here: Home / Android Application Development / Android Advance / Android Retrofit Tutorial to Insert into MySQL Database

Android Retrofit Tutorial to Insert into MySQL Database

November 5, 2015 by Belal Khan 46 Comments

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

Follow Updated Tutorial from this Link
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.
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.

dbConnect.php
PHP
1
2
3
4
5
6
7
8
9
<?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.

insert.php
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
<?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.

retrofit
1
    compile 'com.squareup.retrofit:retrofit:1.9.0'

  • Add internet permission to your manifest.

internet permission
1
    <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.
android retrofit tutorial

android retrofit tutorial

  • Use the following xml code for the above layout.

activity_main.xml
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
<?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.

MainActivity.java
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
//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.

RegisterAPI.java
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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

insertUser()
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
    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.
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

[download id=”1557″]

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 🙂

Sharing is Caring:

  • Tweet
  • Share on Tumblr
  • More
  • Pocket
  • Print
  • Email

Related

Filed Under: Android Advance, Android Application Development Tagged With: android retrofit tutorial, retrofit android, retrofit android example, retrofit android tutorial

About Belal Khan

I am Belal Khan, I am currently pursuing my MCA. In this blog I write tutorials and articles related to coding, app development, android etc.

Comments

  1. vinh says

    November 5, 2015 at 8:20 am

    Can php script handle 2,3 insert query? or we have to create another php file for different insert or query?

    Reply
    • Belal Khan says

      November 5, 2015 at 12:46 pm

      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

      Reply
  2. dimitry says

    November 5, 2015 at 12:43 pm

    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
    • Belal Khan says

      November 5, 2015 at 12:48 pm

      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 😛

      Reply
  3. vinh says

    November 6, 2015 at 6:55 am

    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
  4. vinh says

    November 6, 2015 at 8:05 am

    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
  5. sam says

    November 6, 2015 at 9:51 am

    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
    • Belal Khan says

      November 6, 2015 at 4:24 pm

      you should use http not http://ftp.. ftp is a file transfer protocol thats why you are getting the exception

      Reply
  6. irfan ullah says

    November 18, 2015 at 6:40 pm

    I can not able to download this application plz provide me any other link?

    Reply
  7. Russell says

    December 7, 2015 at 4:33 pm

    Hello

    It is possible if you teach me how to insert a date(datepicker) or time (timepicker) into mysql database..Thxz

    Reply
  8. nabila says

    December 23, 2015 at 2:37 am

    thank you

    Reply
  9. mys says

    January 13, 2016 at 5:41 pm

    where is mysql db create that kind of sql code is missing

    Reply
    • Belal Khan says

      January 13, 2016 at 5:45 pm

      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.

      Reply
  10. FallenAngel says

    January 18, 2016 at 9:03 pm

    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
  11. Najat says

    January 20, 2016 at 11:07 am

    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

    Reply
  12. Najat says

    January 20, 2016 at 12:00 pm

    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?

    Reply
  13. amazingnick says

    January 20, 2016 at 12:34 pm

    very good tutorial.. now I wonder how to add delete and update method.

    Reply
  14. Sophie says

    January 25, 2016 at 10:43 am

    Great post, may I know How Can I show Progress Dialog while storing data to database ?

    Just to provide great experience to users

    Reply
  15. nouraa says

    January 29, 2016 at 11:25 am

    I need script code for confirm password , How to write this code and add it in PHP file ?
    thank you

    Reply
  16. B. van den Engel says

    February 11, 2016 at 8:50 pm

    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
  17. Edward lance lorilla says

    February 21, 2016 at 3:26 pm

    How to update and delete using retrofit?

    Reply
  18. koffi says

    February 29, 2016 at 9:33 pm

    Your Code don’t work. Cant’t use Inetrnet ressource in UI Thread.

    Reply
  19. Denis Costa says

    May 5, 2016 at 8:39 pm

    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
  20. salmanabila says

    May 24, 2016 at 2:38 am

    good tutorial, can I use this tutorial to connect the database with sql server?

    Reply
  21. Pawan says

    June 12, 2016 at 7:14 am

    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
  22. Glenn Maramis says

    June 24, 2016 at 2:42 am

    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
  23. jenith leon says

    July 11, 2016 at 9:36 am

    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
  24. zafer says

    July 15, 2016 at 2:22 pm

    Will you do for Retrofit 2 ?

    Reply
    • Belal Khan says

      July 15, 2016 at 3:27 pm

      Yeah you will get it in upcoming posts.

      Reply
  25. Murthy says

    October 7, 2016 at 6:23 am

    Please Update Tutorial with Retrofit 2.0.

    Reply
  26. hai says

    October 25, 2016 at 9:24 am

    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
    • hai says

      October 25, 2016 at 11:29 am

      Actually,i have noticed there is no problem with codes,but how to set timeout connection or making request proceed for certain time?

      Reply
  27. Anand sharma says

    December 6, 2016 at 11:33 am

    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
    • razu says

      October 9, 2017 at 5:01 am

      just replace localhost with your computer ip address and it should work fine.

      Reply
  28. Abdur Rafay says

    December 9, 2016 at 11:01 am

    I keep getting a toast that says retrofit.Retrofiterror: Connect Timed out
    How do i fix this please help.

    Reply
  29. Mustaufhi says

    December 19, 2016 at 11:30 am

    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
  30. Wil says

    December 21, 2016 at 4:28 pm

    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
  31. yugandhar says

    January 21, 2017 at 6:07 am

    how to add headers while sending request

    Reply
  32. Riyaz says

    January 23, 2017 at 7:53 am

    Bro what we have to do if we wana add profile image too as a parameter. pls help

    Reply
  33. Thiru says

    March 29, 2017 at 6:16 am

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

    Thanks & regards,
    Thiru

    Reply
  34. thiruna says

    April 19, 2017 at 10:47 am

    i have error in toast

    Reply
  35. Ekta says

    May 28, 2017 at 6:40 am

    i am getting error in toast and data is not being inserted in database can you help me..

    Reply
  36. Shubham says

    June 8, 2017 at 3:25 pm

    Followed the same tutorial….404 error it is showing.

    Reply
  37. araf says

    September 26, 2017 at 2:10 am

    how can i fetch data i had register to show information self

    Reply
  38. Amol says

    December 30, 2017 at 10:55 am

    RestAdapter doesnt get resolved please help me out

    Reply
  39. Nur Cahyadi Perdana says

    April 17, 2018 at 3:43 am

    can you help me, i want create login user how to get work ?

    Reply

Leave a Reply to Belal Khan Cancel reply

Your email address will not be published. Required fields are marked *

Search




Download our Android App

Simplified Coding in Google Play

About Me

Belal Khan

Hello I am Belal Khan, founder and owner of Simplified Coding. I am currently pursuing MCA from St. Xavier's College, Ranchi. I love to share my knowledge over Internet.

Connect With Me

Follow @codesimplified
Simplified Coding

Popular Tutorials

  • Android JSON Parsing – Retrieve From MySQL Database
  • Android Login and Registration Tutorial with PHP MySQL
  • Android Volley Tutorial – Fetching JSON Data from URL
  • Android Upload Image to Server using Volley Tutorial
  • Android TabLayout Example using ViewPager and Fragments
  • Retrieve Data From MySQL Database in Android using Volley
  • Firebase Cloud Messaging Tutorial for Android
  • Android Volley Tutorial – User Registration and Login
  • Android Upload Image to Server Using PHP MySQL
  • Android Navigation Drawer Example using Fragments




About Simplified Coding

Simplified Coding is a blog for all the students learning programming. We are providing various tutorials related to programming and application development. You can get various nice and simplified tutorials related to programming, app development, graphics designing and animation. We are trying to make these things simplified and entertaining. We are writing text tutorial and creating video and visual tutorials as well. You can check about the admin of the blog here and check out our sitemap

Quick Links

  • Advertise Here
  • Privacy Policy
  • Disclaimer
  • About
  • Contact Us
  • Write for Us

Categories

Android Advance Android Application Development Android Beginners Android Intermediate Ionic Framework Tutorial JavaScript Kotlin Android Others PHP Advance PHP Tutorial React Native

Copyright © 2017 · Simplified Coding· All rights Reserved. And Our Sitemap.All Logos & Trademark Belongs To Their Respective Owners·

loading Cancel
Post was not sent - check your email addresses!
Email check failed, please try again
Sorry, your blog cannot share posts by email.