Send data to remote server in android using Volley library

    3
    375

    Send data to the remote server in android using Volley library | In this tutorial, we will learn, how to send the data to the remote server in an android application using Volley Library. Android app will perform Volley’s POST request to send data. we are using volley Library because it reduces the complexity to fetch or post data over the network.the main advantage of volley library is, the developer doesn’t need to write lengthy code for accessing the network.We will use WAMP server to communicate with the remote database.

    Download Project – here

     

    Step:-1 Configuring Remote Server

    • Download WAMP Server on your PC. Install it and run the Wamp server. if Wamp server logo turns its color to green its ready to use.

    • Now Open the PHPMyAdmin by hitting “http://localhost/phpmyadmin/” in your browser. The username will be “root” and password will be blank. Click “GO”.
    • Create a Database name it “check”, then create a table inside check database. name it userdata.

    • Table column name will be id, name, email, password as shown in below image.

    Step:-2 Creating PHP file

    • Open www folder inside C drive > wamp> www.
    • Create a folder inside www. name it uses.
    • Inside user folder, create a file name it index.php.
    • Open Index.php file in Notepad++ Editor. and add the following code inside it.make sure file type must be PHP. and save it.
    <?php
    
    $username = $_POST['name'];
    $useremail = $_POST['email'];
    $userpassword = $_POST['password'];
    $user = "root";
    $pass = "";
    $host= "localhost";
    $dbname="check";
    
    $con = mysqli_connect($host,$user,$pass,$dbname);
    $sql="insert into userdata(name,email,password) values('".$username."','".$useremail."','".$userpassword."');";
    if(mysqli_query($con,$sql)){
    	echo  "data inserted";
    	
    }else{	
    	echo "Failed";
    }
    ?>

    Step 3: – Creating Project & adding Dependencies

    Open your Android Studio -> Go to File > New > New project -> Choose BlankActivity > Finish.

    Open your app level build.gradle and add following Volley Library dependencies

    compile 'com.android.volley:volley:1.0.0'

    Step 4: – Add Internet permission 

    Add Internet permission to your AndroidManifest.xml file.

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

    Step 5: – Add Layout File

    Create or add an XML file inside layout folder name it activity_main.xml. this file contains three edit text which holds the value of name, email, password and a button which submit the details to remote server.

    <?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.mytrendin.remotedata.MainActivity">
    
    
        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:ems="10"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_marginTop="59dp"
            android:id="@+id/name"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:hint="name" />
    
        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="textEmailAddress"
            android:ems="10"
            android:layout_below="@+id/name"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_marginTop="29dp"
            android:id="@+id/email"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:hint="email" />
    
        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="textPassword"
            android:ems="10"
            android:id="@+id/password"
            android:hint="password"
            android:layout_below="@+id/email"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_marginTop="32dp"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />
    
        <Button
            android:text="Save"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/password"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_marginTop="27dp"
            android:id="@+id/save"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />
    </RelativeLayout>
    

    Step 6: – Creating Server Url 

    • Open Command Prompt and Type “ipconfig” you will get ipv4 Address as shown in below image.

    • Here my server URL will be
    //http://192.168.43.87/path to index.php file
    
    http://192.168.43.87/user/index.php

    Step 7: –  Create MainActivity.java file

    • Inside MainActivity.java file declare server URL as a string.
    String url = "http://192.168.43.87/user/index.php";
    • Create RequestQueue which is used to hold the HTTP Requests. pass the context in RequestQueue.
    RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
    • HTTP Requests where the response is parsed as a  String. For a POST Request, to add the parameter, a MAP Needs to return and getparam() method needs to be overridden. we will add the name, email, password to Map in the form of key-value pair inside getparam() method to send the data to remote server.
    StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
    
                            Toast.makeText(MainActivity.this, "dfdsfsd"+response, Toast.LENGTH_SHORT).show();
                            Log.i("My success",""+response);
    
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
    
                            Toast.makeText(MainActivity.this, "my error :"+error, Toast.LENGTH_LONG).show();
                            Log.i("My error",""+error);
                        }
                    }){
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
    
                            Map<String,String> map = new HashMap<String, String>();
                            map.put("name",username);
                            map.put("email",useremail);
                            map.put("password",userpassword);
    
    
                            return map;
                        }
                    };

    Related:

    Signin/Signup session management in Android using PHP/MySQL/Shared preferences – Volley Library

    Send images to remote server in android using Volley library

    Parse JSON data and Sort its attributes(price, quantity, names) in Android application

    Periodically send GPS location to Firebase with custom time frame in Android

    send data to remote server using android retrofit Library with PHP MySQL

    Final MainActivity.java will look like this

    package com.mytrendin.remotedata;
    
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;
    
    import com.android.volley.AuthFailureError;
    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;
    
    import java.util.HashMap;
    import java.util.Map;
    
    public class MainActivity extends AppCompatActivity {
    
        EditText name,email,password;
        Button save;
        String url = "http://192.168.43.87/user/index.php";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            name= (EditText) findViewById(R.id.name);
            email= (EditText) findViewById(R.id.email);
            password= (EditText) findViewById(R.id.password);
            save = (Button) findViewById(R.id.save);
            save.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final String username= name.getText().toString();
                    final String useremail= email.getText().toString();
                    final String userpassword= password.getText().toString();
    
                    RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
                    StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
    
                            Toast.makeText(MainActivity.this, "dfdsfsd"+response, Toast.LENGTH_SHORT).show();
                            Log.i("My success",""+response);
    
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
    
                            Toast.makeText(MainActivity.this, "my error :"+error, Toast.LENGTH_LONG).show();
                            Log.i("My error",""+error);
                        }
                    }){
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
    
                            Map<String,String> map = new HashMap<String, String>();
                            map.put("name",username);
                            map.put("email",useremail);
                            map.put("password",userpassword);
    
    
                            return map;
                        }
                    };
                  queue.add(request);
    
                }
            });
    
        }
    }
    

    Step 7: –  Run Application 

    Now run the application and open table inside phpmyadmin you can see that user records have been saved successfully.

    If You are Beginner Learn Android application development from the scratch


    If you really liked the article, please subscribe to our YouTube Channel for videos related to this article.Please find us on Twitter and Facebook.

    3 COMMENTS

    LEAVE A REPLY

    Please enter your comment!
    Please enter your name here