Android MySQL Insert tutorial.In this tutorial,we look at Android MySQL database,saving data to MySQL. We insert data from edittexts into mysql.

  • We use HttpURLConnection class. It will be our HTTP Client
  • We save to MySQL via PHP Code. PHP will be our server side language while mysql our database.
  • We are making a HTTP POST Request. Basically we are sending data to our server.
  • We write through an outputstream,but also read a response from server via inputstream.
  • We do these in background thread using asynctask.

We are using Java programming language.

Video Tutorial(ProgrammingWizards TV Channel)

Well we have a video tutorial as an alternative to this. If you prefer tutorials like this one then it would be good you subscribe to our YouTube channel.

Basically we have a TV for programming where do daily tutorials especially android.

Full Code

In this tutorial we want to see how save or insert data from an edittext to mysql database.

Android MySQL Insert Save

We are using httpurlconnection as our http client. The user will type data then click send to send the data via HTTP.

Our server side language is PHP while our database is mysql.

MySQL table Structure

Here’s our mysql table:

Android PHP MySQL

1. PHP Code

Here’s our php code:

<?php
$host='127.0.0.1';
$username='root';
$pwd='';
$db="spacecraftDB";
$con=mysqli_connect($host,$username,$pwd,$db) or die('Unable to connect');
if(mysqli_connect_error($con))
{
    echo "Failed to Connect to Database ".mysqli_connect_error();
}
$name=$_POST['name'];
$propellant=$_POST['propellant'];
$description=$_POST['description'];
$sql="INSERT INTO spacecraftTB(Name,Propellant,Description) VALUES('$name','$propellant','$description')";
$result=mysqli_query($con,$sql);
if($result)
{
    echo ('Successfully Saved........');

}else
{
    echo('Not saved Successfully............');

}
mysqli_close($con);
?>
2. Java Code.

Android apps can be mainly written in Java or Kotlin. These days however there are many frameworks like Flutter also which use languages like Dart.

In this class we are using Java programming language.

We will have these classes in our project.

(a). Our Spacecraft Class

This is our data object representing a single spacecraft.

package com.tutorials.hp.androidmdmysqlsave.mDataObject;

public class Spacecraft {

    int id;
    String name;
    String propellant;
    String description;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getPropellant() {
        return propellant;
    }

    public void setPropellant(String propellant) {
        this.propellant = propellant;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}
(b). Our DataPackager Class
  • Basically,we package our data here for sending.
  • First we add them to a JSON Object.
  • Then we encode them into UTF-8 format using URLEncorder class.
  • Then we return it as a string ready to be written over the network.
package com.tutorials.hp.androidmdmysqlsave.mMySQL;

import com.tutorials.hp.androidmdmysqlsave.mDataObject.Spacecraft;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Iterator;

public class DataPackager {

    Spacecraft spacecraft;

    public DataPackager(Spacecraft spacecraft) {
        this.spacecraft = spacecraft;
    }

    public String packData()
    {
        JSONObject jo=new JSONObject();
        StringBuffer sb=new StringBuffer();

        try {
            jo.put("Name",spacecraft.getName());
            jo.put("Propellant",spacecraft.getPropellant());
            jo.put("Description",spacecraft.getDescription());

            Boolean firstvalue=true;
            Iterator it=jo.keys();

            do {
                String key=it.next().toString();
                String value=jo.get(key).toString();

                if(firstvalue)
                {
                    firstvalue=false;
                }else
                {
                    sb.append("&");
                }

                sb.append(URLEncoder.encode(key,"UTF-8"));
                sb.append("=");
                sb.append(URLEncoder.encode(value,"UTF-8"));

            }while (it.hasNext());

            return sb.toString();

        } catch (JSONException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
(c). Our Connector Class
package com.tutorials.hp.androidmdmysqlsave.mMySQL;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class Connector {

    public static HttpURLConnection connect(String urlAddress)
    {
        try {

            URL url=new URL(urlAddress);
            HttpURLConnection con= (HttpURLConnection) url.openConnection();

            //SET PROPS
            con.setRequestMethod("POST");
            con.setConnectTimeout(20000);
            con.setReadTimeout(20000);
            con.setDoInput(true);
            con.setDoOutput(true);

            return con;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

}
(d). Our Sender Class
  • Yes,its our Sender class.To send us our data.
  • We send our data in a background thread using AsyncTask,the super class of this sender class.
  • While sending data in background,we show our Progressdialog,starting it in onPreExcecute() and dismissing immediately onPostExecute() is called.
  • We establish an outputStream,write to it using OutputStreamWriter().
  • The OutputStreamWriter() instance,we pass to BufferedWriter() instance.
  • The bufferedWriter() instance writes our data.
  • We then read the server response using bufferedreader instance.
(d). Our MainActivity
  • Launcher activity.
  • Initialize UI like EditTexts.
  • Starts the sender Asynctask on button click,passing on urladdress and edittext.

3. Our Layouts

(a). activity_main.xml

This layout will get inflated into the main activity’s user interface. This will happen via the Activity’s setContentView() method which will require us to pass it the layout.

We will do so inside the onCreate() method of Activity.

content_main.xml
  • Our layout.

4. AndroidManifest.xml

Remember to add permission for internet in your manifest file.

5. Download

Hey,everything is in source code reference that is well commented and easy to understand and can be downloaded below.

Also check our video tutorial it’s more detailed and explained in step by step.

No. Location Link
1. GitHub Direct Download
2. GitHub Browse
3. YouTube Video Tutorial