Android: Volley

8 minutes, 21 seconds

Connect to Web Service on Android with Volley, a networking management framework.

Volley is a framework for Android app to connect with the web service and also managing the connection. It’s useful to connect with RESTful web services, such in this example we will use our Demo API.

If you want to read intro about Android development with Android Studio please go here.

Without further ado lets make our app connected to internet service. We will create a client app, that can receive list of Amazing Places in the world.

Create an Android Project

Open up your Android Studio, and create a new project with Empty Activity, leave every options while creating the project to defaults.

Install Volley via Gradle

Similar to CocoaPods on iOS, we use Gradle to install dependancies. Expand the Gradle Scripts, open the build.gradle (Module: app) file.


dependencies {
  compile 'com.android.volley:volley:1.0.0'
  ...
}

Add Permission

Add this line of code inside AndroidManifest.xml, it’s after <manifest /> tag, outside <application></application> tag.


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

On Android, we have to declare that we want to use internet explicitly.

Keep the URL Handy

For custom API develoment we probably changes the base full API URL address, depends on the develoment or production, but the API point is the same.

Why not we make the API a bit more manageable.

First create the EndPoints class with BASE_URL as a static variable.


public class EndPoints {
  public static final String BASE_URL = "https://irekaweb.com/api/demo";
}

We will see how this get connected when we want to request API.

Request JSON

Add this declaration of your URL.


public final String LIST = EndPoints.BASE_URL+"/amazing_places/list";

The full path for LIST is will be : ‘https://irekaweb.com/api/demo/amazing_places/list‘ with GET method.

It’s a good idea to try to call an API request using tool like Postman to verify the result before we do the handling inside the app.

Add this codes inside ‘onCreate‘ function.


// Initiate the Volley Queue
RequestQueue queue = Volley.newRequestQueue(this);

// This StringRequest is long
// It requires the type of request POST, GET, PUT..
// require the URL
// and also will have callbacks for success and error.
StringRequest request = new StringRequest(Request.Method.GET,
  REDDIT_URL,
  new Response.Listener<String>(){

  @Override
  public void onResponse(String response) {
    
    // Print out the success response
    Log.i("RESPONSE",response);

  }

}, new Response.ErrorListener(){

  @Override
  public void onErrorResponse(VolleyError error){

    // Log the error
    NetworkResponse response = error.networkResponse;
    if(response != null && response.data != null){
      String errorString = new String(response.data);
      Log.i("ERROR", errorString);
    }

  }
}
);

// This make the connection try to retry if any 
// minor error happen when try to connect.
// Optional but very helpful
request.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f));

// Ultimate request, to add request to the queue and execute it!
queue.add(request);

Request POST with Parameter

If you want to login or something, there would be a POST method to call with parameter.


// Instantiate the queue    
RequestQueue queue = Volley.newRequestQueue(this);

String URL = EndPoints.BASE_URL + "/call";

StringRequest request = new StringRequest(Request.Method.POST, URL,
      new Response.Listener<String>()
      {
        @Override
        public void onResponse(String response) {

          Log.d("onResponse", response);

        }
      },
      new Response.ErrorListener()
      {
        @Override
        public void onErrorResponse(VolleyError error) {

          NetworkResponse response = error.networkResponse;
          String errorMsg = "";
          if(response != null && response.data != null){
            String errorString = new String(response.data);
            Log.i("log error", errorString);
          }
        }
      }
    ) {
      @Override
      protected Map<String, String> getParams()
      {

        Map<String, String> params = new HashMap<String, String>();
        params.put("key_1","value_1");
        params.put("key_2", "value_2");
        Log.i("sending ", params.toString());

        return params;
      }

    };


// Add the realibility on the connection.
request.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f));

// Start the request immediately
queue.add(request);    

Reading JSON Return Value

Inside the stringRequest there is a override function alled ‘onResponse(String response)’ which return a String respond. Usually it’s being return in JSON format (you will need to refer to API docs).

Simple JSON

For example here is the JSON as response. This example is a simple JSON text, that have 2 keys and values.


{
  "name": "Hijazi",
  "image_name": "my_image"
}

Here is how to read the data inside the JSON format. We need to encapsulate in try/catch closure because we try to convert from String to JSONObject, and probably the String is not compatible to be a JSON, if error happen it will fall into catch closure.


try {
  JSONObject obj = new JSONObject(response);
  String name = obj.getString("name");
} catch (JSONException e) {
  e.printStackTrace();
}

Array JSON

For example here is the JSON as response. This example is a call to ‘amazing_places/list’.


[
  {
    "id": "1",
    "title": "Tunnel of Love, Ukraine",
    "coordinate": "50.751354, 26.049294",
    "image_url": "http://cdn.tourismontheedge.com/wp-content/uploads/2012/08/tunnel-of-love-ukraine.jpg",
    "description": null,
    "created_at": null,
    "updated_at": null,
    "name": null,
    "address": null,
    "ap_category_id": null,
    "ap_country_id": null
  },
  ...
]

API Creation With Laravel

Application Programming Interface or (API) is way to communicate to the server. There is specific REST URL that can be call that can have return back from server.

Using framework like Laravel help you to create API on the server and let mobile apps to communicate with your server.

Returning Result

Use respond codes like 200 for OK and 201 for created. Followed with your response in JSON format.

Here is the example to return a 200 : OK result, where we return the JSON file.


public function demo_list(){
     
  $places = \DB::table('ap_places')->get();
  $response = \Response::json($places)->setStatusCode(200, 'Success'); 
                      
  return $response;
  
}

Handling API Error

There is way to respond to client if there is error or inintended respond from the server.

Use respond code like 400 for Bad Request, 401 for Unauthorized, 403 for Forbidden and 404 for Not Found.

Return a message for users with layman term is a good way to inform user about what’s happened.

This example when we want return error code with message.


// declare to use Response
use Response;
$result = \Response::json(['message'=>'You are unauthorized.'])->setStatusCode(401, 'Unauthorized');
return $result;

Which will return:


// Status 401 : Unauthorized
{
  "message": "You are unauthorized."
}

Resources

Android Volley Docs
Reddit API Docs
Response Codes