Insert data from App to MySQL Database in Android in 10 minutes!

In this tutorial we would learn how you can insert data from app to mysql database in Android. This tutorial is helpful for beginner developers who wish to understand dynamic content management in android development. In this tutorial we are going to do some basic programming and learn to insert data from application to MySQL database Android PHP .

What is MySQL?

SQL is a domain-specific language used in programming and designed for managing data held in a relational database management system, or for stream processing in a relational data stream management system. 

What would you learn in this tutorial?

  1. Starting a new project in Android Studio.
  2. Creating a database on your online server.
  3. Make a table in your database.
  4. Upload the PHP script on your server.
  5. Testing the PHP script.
  6. Adding internet permission in your project’s AndroidManifest.xml file.
  7. Add Org.Apache.Http.Legacy in your project.
  8. Adding two EditText and one button in your layout file.
  9. Declare EditText and button objects in your Activity & Assign their ID’s to them.
  10. Define method to get data from EditText into String variables.
  11. Defining AsyncTask method class in your Activity.

Create Library modules by yourself in Android! LEARN NOW!

Insert data from app to MySQL Database in Android

Creating a database on your online server:

Database is very important because without database there is no possible way to creating tables. Now make an database on your online server or your demo website.

Make a table in your database

Create a table in your database named as GetDataTable and inside that table create three columns id, name, email. 

Creating table for inserting data from app to MySQL database
Creating Table for inserting data from app to Mysql database

Upload the PHP script on your server

After finishing table creation process just upload the below two PHP scripts on your server using file manager. There are two different type of files present here first one is DatabaseConfig.php file and second is get_data.php file.

NOTE :- Please change the details of your server in DatabaseConfig.php file.

<?php

//Define your host here.
$HostName = "mysql.hostinger.in";

//Define your database username here.
$HostUser = "u288012116_json";

//Define your database password here.
$HostPass = "N1c45hlf";

//Define your database name here.
$DatabaseName = "u288012116_json";

?>

Code for get_data.php file

<?php

include 'DatabaseConfig.php' ;
 
 $con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);
 
 $name = $_POST['name'];
 $email = $_POST['email'];

 $Sql_Query = "insert into GetDataTable (name,email) values ('$name','$email')";
 
 if(mysqli_query($con,$Sql_Query)){
 
 echo 'Data Submit Successfully';
 
 }
 else{
 
 echo 'Try Again';
 
 }
 mysqli_close($con);
?>

Testing the PHP script

After done uploading procedure just open the get_data.php file URL in your web browser and you can see that its showing us the Data Submit Successfully message and when you open the PhpMyAdmin control panel there is a blank value inserted in your table.

This value is blank because there is no such data present for insertion.

Adding internet permission in your project’s AndroidManifest.xml file

Next step is to add internet permission in your AndroidManifest.xml file.

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

Now add Org.Apache.Http.Legacy in your project.

Adding two EditText and one button in your layout file

Open your project’s activity_main.xml file and paste the below code to insert two edittext and one button in it.

<TextView
    android:text="Submit Data to Server"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:id="@+id/textView"
    android:gravity="center"
    android:textSize="20dp"
    android:textColor="#000000"
    />

<EditText
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:inputType="textPersonName"
    android:hint="Enter Name"
    android:ems="10"
    android:layout_below="@+id/textView"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="30dp"
    android:id="@+id/editText2"
    android:gravity="center"/>

<EditText
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:inputType="textEmailAddress"
    android:ems="10"
    android:hint="Enter Email"
    android:layout_marginTop="46dp"
    android:id="@+id/editText3"
    android:layout_below="@+id/editText2"
    android:layout_centerHorizontal="true"
    android:gravity="center"
     />

<Button
    android:text="Submit Data"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/editText3"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="38dp"
    android:id="@+id/button" />

Declare EditText and button objects in your Activity & Assign their ID’s to them

String ServerURL = "http://androidblog.esy.es/AndroidJSon/get_data.php" ;
EditText name, email ;
Button button;
String TempName, TempEmail ;

name = (EditText)findViewById(R.id.editText2);
email = (EditText)findViewById(R.id.editText3);
button = (Button)findViewById(R.id.button);

Define method to get data from EditText into String variables

public void GetData(){

    TempName = name.getText().toString();

    TempEmail = email.getText().toString();

 }

Defining AsyncTask method class in your Activity to Android PHP Insert data to server

public void InsertData(final String name, final String email){

    class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {

            String NameHolder = name ;
            String EmailHolder = email ;

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

            nameValuePairs.add(new BasicNameValuePair("name", NameHolder));
            nameValuePairs.add(new BasicNameValuePair("email", EmailHolder));

            try {
                HttpClient httpClient = new DefaultHttpClient();

                HttpPost httpPost = new HttpPost(ServerURL);

                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                HttpResponse httpResponse = httpClient.execute(httpPost);

                HttpEntity httpEntity = httpResponse.getEntity();


            } catch (ClientProtocolException e) {

            } catch (IOException e) {

            }
            return "Data Inserted Successfully";
        }

        @Override
        protected void onPostExecute(String result) {

            super.onPostExecute(result);

            Toast.makeText(MainActivity.this, "Data Submit Successfully", Toast.LENGTH_LONG).show();

        }
    }

    SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();

    sendPostReqAsyncTask.execute(name, email);
}

MainActivity.java code

package com.androidjson.insertdata_androidjsoncom;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    String ServerURL = "http://androidblog.esy.es/AndroidJSon/get_data.php" ;
    EditText name, email ;
    Button button;
    String TempName, TempEmail ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        name = (EditText)findViewById(R.id.editText2);
        email = (EditText)findViewById(R.id.editText3);
        button = (Button)findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                GetData();

                InsertData(TempName, TempEmail);

            }
        });
    }

   public void GetData(){

       TempName = name.getText().toString();

       TempEmail = email.getText().toString();

    }

    public void InsertData(final String name, final String email){

        class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
            @Override
            protected String doInBackground(String... params) {

                String NameHolder = name ;
                String EmailHolder = email ;

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

                nameValuePairs.add(new BasicNameValuePair("name", NameHolder));
                nameValuePairs.add(new BasicNameValuePair("email", EmailHolder));

                try {
                    HttpClient httpClient = new DefaultHttpClient();

                    HttpPost httpPost = new HttpPost(ServerURL);

                    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    HttpResponse httpResponse = httpClient.execute(httpPost);

                    HttpEntity httpEntity = httpResponse.getEntity();


                } catch (ClientProtocolException e) {

                } catch (IOException e) {

                }
                return "Data Inserted Successfully";
            }

            @Override
            protected void onPostExecute(String result) {

                super.onPostExecute(result);

                Toast.makeText(MainActivity.this, "Data Submit Successfully", Toast.LENGTH_LONG).show();

            }
        }

        SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();

        sendPostReqAsyncTask.execute(name, email);
    }

}

Code for activity_main.xml layout file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    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"
    tools:context="com.androidjson.insertdata_androidjsoncom.MainActivity">

    <TextView
        android:text="Submit Data to Server"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:id="@+id/textView"
        android:gravity="center"
        android:textSize="20dp"
        android:textColor="#000000"
        />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:hint="Enter Name"
        android:ems="10"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        android:id="@+id/editText2"
        android:gravity="center"/>

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:ems="10"
        android:hint="Enter Email"
        android:layout_marginTop="46dp"
        android:id="@+id/editText3"
        android:layout_below="@+id/editText2"
        android:layout_centerHorizontal="true"
        android:gravity="center"
         />

    <Button
        android:text="Submit Data"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText3"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="38dp"
        android:id="@+id/button" />

</RelativeLayout>

Code for AndroidManifest.xml file

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

    <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">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

We Recommend

Don't Miss Out!

Get the very best of Android Hire in your inbox. News, How To,  Apps and games & Tutorials.