Android PHP Insert data from App to MySQL Database

Pushing data from android application to server is very important feature for every android application. That makes our application dynamic. This tutorial is helpful for beginners 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 .

Contents in this project Android PHP Insert data from Application to MySQL Database.

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

1. Watch the live demo video :

2. Starting a new project in Android Studio :

After seeing the demo work video next step is to start a new application project in Android Studio with blank activity.

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

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

5. 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. Please change the details of your server in DatabaseConfig.php file.

Code for 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);
?>

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

7. 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"/>

8. Add Org.Apache.Http.Legacy in your project.

9. 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" />

 10. 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);

 11. Define method to get data from EditText into String variables :

public void GetData(){

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

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

 }

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

Final Code of Android PHP Insert data to server :

Code for MainActivity.java file.

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>

Screenshot:

Android PHP Insert data

Download Code

Leave a Reply

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