Android MySQL - Insert/Save - Material EditTexts

android networking

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.
package com.tutorials.hp.androidmdmysqlsave.mMySQL;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.EditText;
import android.widget.Toast;

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

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;

public class Sender extends AsyncTask<Void,Void,String> {

    Context c;
    String urlAddress;
    EditText nameTxt,propellantTxt,descTxt;

    Spacecraft spacecraft;

    ProgressDialog pd;

    public Sender(Context c, String urlAddress, EditText nameTxt, EditText propellantTxt, EditText descTxt) {
        this.c = c;
        this.urlAddress = urlAddress;
        this.nameTxt = nameTxt;
        this.propellantTxt = propellantTxt;
        this.descTxt = descTxt;

        spacecraft=new Spacecraft();
        spacecraft.setName(nameTxt.getText().toString());
        spacecraft.setPropellant(propellantTxt.getText().toString());
        spacecraft.setDescription(descTxt.getText().toString());
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        pd=new ProgressDialog(c);
        pd.setTitle("Send");
        pd.setMessage("Sending...Please wait");
        pd.show();
    }

    @Override
    protected String doInBackground(Void... params) {
        return this.send();
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        pd.dismiss();

        if(s==null)
        {
            Toast.makeText(c,"Unsuccessful,Null returned",Toast.LENGTH_SHORT).show();
        }else
        {
            if(s=="Bad Response")
            {
                Toast.makeText(c,"Unsuccessful,Bad Response returned",Toast.LENGTH_SHORT).show();

            }else
            {
                Toast.makeText(c,"Successfully Saved",Toast.LENGTH_SHORT).show();

                //CLEAR UI
                nameTxt.setText("");
                propellantTxt.setText("");
                descTxt.setText("");
            }
        }

    }

    private String send()
    {
        HttpURLConnection con=Connector.connect(urlAddress);
        if(con==null)
        {
            return null;
        }

        try {

            OutputStream os=con.getOutputStream();

            //WRITE
            BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
            bw.write(new DataPackager(spacecraft).packData());

            bw.flush();
            //RELEASE
            bw.close();
            os.close();

            //SUCCESS OR NOT??
            int responseCode=con.getResponseCode();
            if(responseCode==con.HTTP_OK)
            {
                BufferedReader br=new BufferedReader(new InputStreamReader(con.getInputStream()));
                StringBuffer response=new StringBuffer();

                String line;
                while ((line=br.readLine()) != null)
                {
                    response.append(line);
                }

                br.close();
                return response.toString();
            }else {
                return "Bad Response";
            }

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

        return null;
    }
}
(d). Our MainActivity
  • Launcher activity.
  • Initialize UI like EditTexts.
  • Starts the sender Asynctask on button click,passing on urladdress and edittext.
package com.tutorials.hp.androidmdmysqlsave;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;

import com.tutorials.hp.androidmdmysqlsave.mMySQL.Sender;

public class MainActivity extends AppCompatActivity {

    String urlAddress="http://10.0.2.2/android/spacecraft.php";
    EditText nameTxt,propellantTxt,descTxt;
    Button saveBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        nameTxt= (EditText) findViewById(R.id.nameEditTxt);
        propellantTxt= (EditText) findViewById(R.id.propellantEditTxt);
        descTxt= (EditText) findViewById(R.id.descEditTxt);
        saveBtn= (Button) findViewById(R.id.saveBtn);

        saveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Sender s=new Sender(MainActivity.this,urlAddress,nameTxt,propellantTxt,descTxt);
                s.execute();
            }
        });

    }

}

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.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
    tools:context="com.tutorials.hp.androidmdmysqlsave.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>
content_main.xml
  • Our layout.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.tutorials.hp.androidmdmysqlsave.MainActivity"
    tools:showIn="@layout/activity_main">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="?attr/actionBarSize"
        android:orientation="vertical"
        android:paddingLeft="15dp"
        android:paddingRight="15dp"
        android:paddingTop="50dp">

        <android.support.design.widget.TextInputLayout
            android:id="@+id/nameLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/nameEditTxt"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:singleLine="true"
                android:hint= "Name" />
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:id="@+id/propellantLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/propellantEditTxt"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"

                android:hint="Propellant" />
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:id="@+id/descLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/descEditTxt"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"

                android:hint="Description" />

        </android.support.design.widget.TextInputLayout>

        <Button android:id="@+id/saveBtn"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Save"
            android:clickable="true"
            android:background="@color/colorAccent"
            android:layout_marginTop="40dp"
            android:textColor="@android:color/white"/>

    </LinearLayout>
</RelativeLayout>

4. AndroidManifest.xml

Remember to add permission for internet in your manifest file.

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

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

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

About Me

My name is Oclemy, after recently finishing my Software Engineering undergraduate program, am now dedicating alot of time to my two babies: Camposha.info and my YouTube Channel ProgrammingWizards TV apart from my daily work.

Am committed to making them world class resources in the next few years. Help me by subscribing to my YouTube Channel ProgrammingWizards TV and sharing my articles.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post