Saturday, 11 February 2017

Sending POST Request to Internet Using Android Volley

android volley library - android tech point
Android Volley Library Tutorial

Android Volley is an library for network operations in android development. It is a very light weight framework and most importantly, very fast for network operations. It has facility to get the raw string, image or JSON data over the network efficently. One of the benifit that I like the most if you can easily use volley in your activity as it automatically sends the request in separate thread. And also maintains a queue for the requests.
Note that volley is not for large data downloads as it holds all the data in memory. For large downloading use the DownloadManager.
Here is the demo video for this app.

Dependency for android volley

Minimum requirement for android volley Android 2.2 (API Level 8) or higher. Now come towards tutorial for android volley.

Steps for using Volley

  • Add the uses-permission in Android Manifest.xml file.
    <uses-permission android:name="android.permission.INTERNET"/>
  • Add the dependency in build.gradle (Module: app)
    compile 'com.android.volley:volley:1.0.0'
  • Write code for sending request in MainActivity.java
  • Write the server side code. I am using xampp and sending request to localhost. Follow tutorial here to configure xampp for accessing from other devices.
You can get the complete project at Github Repository. Or you can get the code below in this post.

MainAcitivty.java

package com.androidtechpoint.demo.androidvolley;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
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 {
TextView _name, _email, _response;
android.support.v7.widget.AppCompatButton _sendRequest;
ProgressBar _proProgressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Hooking the UI views for usage
_name = (TextView) findViewById(R.id.name);
_email = (TextView) findViewById(R.id.email);
_response = (TextView) findViewById(R.id.response);
_proProgressBar = (ProgressBar) findViewById(R.id.progressBar);
_sendRequest = (AppCompatButton) findViewById(R.id.send_request);
//hooking onclick listener of button
_sendRequest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
//this is the url where you want to send the request
//TODO: replace with your own url to send request, as I am using my own localhost for this tutorial
String url = "http://192.168.1.7/AndroidVolley/androidVolley.php";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Display the response string.
_response.setText(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
_response.setText("That didn't work!");
}
}) {
//adding parameters to the request
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("name", _name.getText().toString());
params.put("email", _email.getText().toString());
return params;
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
});
}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
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.androidtechpoint.demo.androidvolley.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name" />
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Your Name" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Email" />
<EditText
android:id="@+id/email"
android:inputType="textEmailAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Your Email" />
<android.support.v7.widget.AppCompatButton
android:id="@+id/send_request"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send Request" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Response From Server"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="@+id/response"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="invisible" />
</LinearLayout>

androidvolley.php

<?php
$name = trim($_POST['name']);
$email = trim($_POST['email']);
echo "Hello $name! Welcome to android Tech Point.\nYour email is $email";
?>

In case of error

If you get some error, the first thing you should check is permissions in android androidManifest.xml and build.gradle. If you still get the error feel free to comment below or contact me at farooqahmadkhan003@gmail.com.

29 comments:

  1. The application is exclusively available on its official website and should be downloaded from the site of Mobdro application mobdro

    ReplyDelete
  2. Thanks for your informative blog!!! Keep on updating your with such awesome information.

    Android Online Training

    ReplyDelete
  3. The information you provide is deam good. This information helps lot of user to update their knowledge in android side.Thanks for sharing.Anybody want to learn
    Android Training in Chennai

    ReplyDelete
  4. you have post an very useful post. Its very interesting and useful to me. and i have learnt lots of new information from your blog share. keep it up. thank you.Android Training in Chennai | Web Designing Training in Chennai

    ReplyDelete
  5. I am using your code but when I click on submit button the app is got crashed, and by verifying logcat it gives null pointer exception.

    ReplyDelete
  6. Nice and good article.. it is very useful for me to learn and understand easily.. thanks for sharing your valuable information and time.. please keep updating. Selenium Training in Chennai | Software Testing Training in Chennai

    ReplyDelete
  7. Modbro tv android is the best app available in the market for browsing movies, videos & shows
    Modbro tv android

    ReplyDelete
  8. and what about ProgressBar..... ? why you don't use it..

    ReplyDelete
  9. Yes you can use that, this is actually just a demo to use volley.

    ReplyDelete
  10. Worked it perfectly.thanks for the blog.

    ReplyDelete
  11. The tutorial is amazing. Could you please help me with how to query mysql using this post variable received and how to send that result back to android

    ReplyDelete
    Replies
    1. hey there!
      you can use the variables in query like
      $query = "select * from table where name=" . $name . " and email =" . $email;
      Though it would be better if you use bind parameters, you can do that if you are using MYSQLi in the following way:
      $stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
      $stmt->bind_param("sss", $firstname, $lastname, $email);
      The "sss" argument lists the types of data that the parameters are. The argument may be one of four types:

      i - integer
      d - double
      s - string
      b - BLOB

      Delete
  12. This comment has been removed by the author.

    ReplyDelete
  13. This comment has been removed by the author.

    ReplyDelete


  14. Your new valuable key points imply much a person like me and extremely more to my office workers. With thanks.
    UNIX Shell scripting training in chennai
    ORACLE apps finance training in chennai
    Informatica Online Training

    ReplyDelete
  15. Unexpected response code 301 for http://api.hallohours.in/api/signup/
    ERROR Come

    ReplyDelete
  16. This comment has been removed by the author.

    ReplyDelete
  17. not working api is expierd

    ReplyDelete
  18. This is an awesome post.Really very informative and creative contents.This concept is a good way to enhance the knowledge.
    Java training in Chennai


    ReplyDelete
  19. it is giving only one error android.volley.timeouterror

    ReplyDelete
  20. This blog has all it takes to be called the best blog.
    Mason Soiza

    ReplyDelete
  21. I am getting response 400 when i use this code Can u Help me. I sent my Code to your email. PLease Help me

    ReplyDelete
  22. Good videos don't beat people over the head with sales messages but do include strong calls to action. 無料

    ReplyDelete