Android Volley Insert Multiple Data in MySQL Database Tutorial

Android Volley Post Request with parameters Example using StringRequest and Show server response echo message in App on successfully submitting.

In this tutorial we would going to use Android’s most famous library known as Volley .This library is freely available for every developer. You can do multiple network data transmitting work using Volley. So here is the complete step by step tutorial for Android Volley Insert Multiple Data into MySQL Database Tutorial.

Follow the below steps for Android Volley Tutorial :-

1. Create a database in PhpMyAdmin.

2. Create a new table in database name as UserInfo with four columns id, first_name, last_name, email . Set id as primary key.

 

3. Upload the below PHP script with your database configuration. In DatabaseConfig.php file you have to set your server PhpMyAdmin HostName, Host Password, Host User, Database Name.

Code for DatabaseConfig.php file.

<?php

//Define your host here.
$HostName = "localhost";

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

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

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

?>

Code for insert_record.php file.

<?php

include 'DatabaseConfig.php';

 $con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);
 
 $f_name = $_POST['first_name'];
 $l_name = $_POST['last_name'];
 $email = $_POST['email'];
 
 $Sql_Query = "insert into UserInfo (first_name,last_name,email) values ('$f_name','$l_name','$email')";
 
 if(mysqli_query($con,$Sql_Query)){
 
 echo 'Data Inserted Successfully';
 
 }
 else{
 
 echo 'Try Again';
 
 }
 mysqli_close($con);
?>

 

4. Start a new android application development project.

5. Add internet permission in AndroidManifest.xml file.

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

 

6. Add compile ‘com.android.volley:volley:1.0.0’ library file in build.gradle(Module:app) file. So open it.

build-gradle

 

7. Add compile ‘com.android.volley:volley:1.0.0’ inside dependencies block.

 

8. Create Three EditText and one button in activity layout file.

<EditText
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:inputType="textPersonName"
    android:hint="First Name"
    android:gravity="center"
    android:ems="10"
    android:id="@+id/editTextFirstName"
    android:layout_marginTop="30dp"
    />

<EditText
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:inputType="textPersonName"
    android:hint="Last Name"
    android:gravity="center"
    android:ems="10"
    android:id="@+id/editTextLastName"
    android:layout_below="@+id/editTextFirstName"
    />

<EditText
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:inputType="textEmailAddress"
    android:ems="10"
    android:id="@+id/editTextEmail"
    android:layout_below="@+id/editTextLastName"
    android:hint="Email"
    android:gravity="center"/>

<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Insert Record on Server"
    android:id="@+id/ButtonInsert"
    android:layout_below="@+id/editTextEmail"
    android:layout_centerHorizontal="true" />

 

9. Create button, EditText, RequestQueue, String, ProgressDialog and HttpUrl , button objects in MainActivity.java file.

// Creating EditText.
EditText FirstName, LastName, Email ;

// Creating button;
Button InsertButton;

// Creating Volley RequestQueue.
RequestQueue requestQueue;

// Create string variable to hold the EditText Value.
String FirstNameHolder, LastNameHolder, EmailHolder ;

// Creating Progress dialog.
ProgressDialog progressDialog;

// Storing server url into String variable.
String HttpUrl = "https://android-examples.000webhostapp.com/insert_record.php";

 

10. Assign ID’s to all of them.

// Assigning ID's to EditText.
FirstName = (EditText) findViewById(R.id.editTextFirstName);
LastName = (EditText) findViewById(R.id.editTextLastName);
Email = (EditText) findViewById(R.id.editTextEmail);

// Assigning ID's to Button.
InsertButton = (Button) findViewById(R.id.ButtonInsert);

// Creating Volley newRequestQueue .
requestQueue = Volley.newRequestQueue(MainActivity.this);

progressDialog = new ProgressDialog(MainActivity.this);

 

11. Creating method to get value from EditText.

public void GetValueFromEditText(){

    FirstNameHolder = FirstName.getText().toString().trim();
    LastNameHolder = LastName.getText().toString().trim();
    EmailHolder = Email.getText().toString().trim();

}

 

12. Adding click listener to button.

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

    }
});

 

13. Creating StringRequest method.

// Creating string request with post method.
StringRequest stringRequest = new StringRequest(Request.Method.POST, HttpUrl,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String ServerResponse) {

                // Hiding the progress dialog after all task complete.
                progressDialog.dismiss();

                // Showing response message coming from server.
                Toast.makeText(MainActivity.this, ServerResponse, Toast.LENGTH_LONG).show();
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

                // Hiding the progress dialog after all task complete.
                progressDialog.dismiss();

                // Showing error message if something goes wrong.
                Toast.makeText(MainActivity.this, volleyError.toString(), Toast.LENGTH_LONG).show();
            }
        }) {
    @Override
    protected Map<String, String> getParams() {

        // Creating Map String Params.
        Map<String, String> params = new HashMap<String, String>();

        // Adding All values to Params.
        params.put("first_name", FirstNameHolder);
        params.put("last_name", LastNameHolder);
        params.put("email", EmailHolder);

        return params;
    }

};

 

14. Calling RequestQueue to call the stringRequest method.

// Creating RequestQueue.
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);

// Adding the StringRequest object into requestQueue.
requestQueue.add(stringRequest);

 

15. Calling StringRequest and GetValueFromEditText() method inside the button click scope.

// Adding click listener to button.
InsertButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        // Showing progress dialog at user registration time.
        progressDialog.setMessage("Please Wait, We are Inserting Your Data on Server");
        progressDialog.show();

        // Calling method to get value from EditText.
        GetValueFromEditText();

        // Creating string request with post method.
        StringRequest stringRequest = new StringRequest(Request.Method.POST, HttpUrl,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String ServerResponse) {

                        // Hiding the progress dialog after all task complete.
                        progressDialog.dismiss();

                        // Showing response message coming from server.
                        Toast.makeText(MainActivity.this, ServerResponse, Toast.LENGTH_LONG).show();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {

                        // Hiding the progress dialog after all task complete.
                        progressDialog.dismiss();

                        // Showing error message if something goes wrong.
                        Toast.makeText(MainActivity.this, volleyError.toString(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {

                // Creating Map String Params.
                Map<String, String> params = new HashMap<String, String>();

                // Adding All values to Params.
                params.put("first_name", FirstNameHolder);
                params.put("last_name", LastNameHolder);
                params.put("email", EmailHolder);

                return params;
            }

        };

        // Creating RequestQueue.
        RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);

        // Adding the StringRequest object into requestQueue.
        requestQueue.add(stringRequest);

    }
});

 Complete source code :

Code for MainActivity.java file.

package com.android_examples.volleysenddata2server_android_examplescom;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
import android.widget.EditText;
import android.widget.Button;

import java.util.HashMap;
import java.util.Map;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

public class MainActivity extends AppCompatActivity {

    // Creating EditText.
    EditText FirstName, LastName, Email ;

    // Creating button;
    Button InsertButton;

    // Creating Volley RequestQueue.
    RequestQueue requestQueue;

    // Create string variable to hold the EditText Value.
    String FirstNameHolder, LastNameHolder, EmailHolder ;

    // Creating Progress dialog.
    ProgressDialog progressDialog;

    // Storing server url into String variable.
    String HttpUrl = "https://android-examples.000webhostapp.com/insert_record.php";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Assigning ID's to EditText.
        FirstName = (EditText) findViewById(R.id.editTextFirstName);
        LastName = (EditText) findViewById(R.id.editTextLastName);
        Email = (EditText) findViewById(R.id.editTextEmail);

        // Assigning ID's to Button.
        InsertButton = (Button) findViewById(R.id.ButtonInsert);

        // Creating Volley newRequestQueue .
        requestQueue = Volley.newRequestQueue(MainActivity.this);

        progressDialog = new ProgressDialog(MainActivity.this);

        // Adding click listener to button.
        InsertButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // Showing progress dialog at user registration time.
                progressDialog.setMessage("Please Wait, We are Inserting Your Data on Server");
                progressDialog.show();

                // Calling method to get value from EditText.
                GetValueFromEditText();

                // Creating string request with post method.
                StringRequest stringRequest = new StringRequest(Request.Method.POST, HttpUrl,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String ServerResponse) {

                                // Hiding the progress dialog after all task complete.
                                progressDialog.dismiss();

                                // Showing response message coming from server.
                                Toast.makeText(MainActivity.this, ServerResponse, Toast.LENGTH_LONG).show();
                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError volleyError) {

                                // Hiding the progress dialog after all task complete.
                                progressDialog.dismiss();

                                // Showing error message if something goes wrong.
                                Toast.makeText(MainActivity.this, volleyError.toString(), Toast.LENGTH_LONG).show();
                            }
                        }) {
                    @Override
                    protected Map<String, String> getParams() {

                        // Creating Map String Params.
                        Map<String, String> params = new HashMap<String, String>();

                        // Adding All values to Params.
                        params.put("first_name", FirstNameHolder);
                        params.put("last_name", LastNameHolder);
                        params.put("email", EmailHolder);

                        return params;
                    }

                };

                // Creating RequestQueue.
                RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);

                // Adding the StringRequest object into requestQueue.
                requestQueue.add(stringRequest);

            }
        });

    }

    // Creating method to get value from EditText.
    public void GetValueFromEditText(){

        FirstNameHolder = FirstName.getText().toString().trim();
        LastNameHolder = LastName.getText().toString().trim();
        EmailHolder = Email.getText().toString().trim();

    }

}

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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.android_examples.volleysenddata2server_android_examplescom.MainActivity"
    android:layout_margin="15dp">

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:hint="First Name"
        android:gravity="center"
        android:ems="10"
        android:id="@+id/editTextFirstName"
        android:layout_marginTop="30dp"
        />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:hint="Last Name"
        android:gravity="center"
        android:ems="10"
        android:id="@+id/editTextLastName"
        android:layout_below="@+id/editTextFirstName"
        />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:ems="10"
        android:id="@+id/editTextEmail"
        android:layout_below="@+id/editTextLastName"
        android:hint="Email"
        android:gravity="center"/>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Insert Recode on Server"
        android:id="@+id/ButtonInsert"
        android:layout_below="@+id/editTextEmail"
        android:layout_centerHorizontal="true" />

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

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        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>

Screenshots :

Android Volley

Download Source Code