Android working with Volley Library.

By in , , ,
One comment

Main Objective of this blog post is to explain how to Volley library in an Android Studio .Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster. Volley is available on GitHub.

 

Advantages of Using Volley:

  •  Automatic scheduling of network requests.. It means that Volley will be taking care of all the network requests your app executes for fetching response or image from the web.
  • Transparent disk and memory response caching with standard HTTP cache coherence.
  • Volley provides powerful cancellation request API. It means that you can cancel a single request or you can set blocks or scopes of requests to cancel.
  • Strong ordering that makes it easy to correctly populate your UI with data fetched asynchronously from the network.
  • Debugging and tracing tools.

How to Get Started?

Open build.gradle and add volley support by adding under dependencies section.

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'

activity_main.class

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.admin.volleylibrary.MainActivity">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    >


    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="30dp"
        android:layout_marginLeft="20dp"
        >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="NAME :"
            android:textSize="16dp"
            android:textColor="@color/colorPrimaryDark"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textview_name"
            android:textSize="16dp"
            android:textColor="#000000"
            />

    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="30dp"
        android:layout_marginLeft="20dp"
        >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Location :"
            android:textSize="16dp"
            android:textColor="@color/colorPrimaryDark"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textview_location"
            android:textSize="16dp"
            android:textColor="#000000"
            />

    </LinearLayout>


</LinearLayout>
</RelativeLayout>

MainActivity.class

package com.example.admin.volleylibrary;

import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NoConnectionError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

import static android.icu.lang.UCharacter.GraphemeClusterBreak.V;
import static com.example.admin.volleylibrary.Constant.first;

public class MainActivity extends AppCompatActivity {

    ProgressDialog progressDialog;
    TextView textview_name,textview_location;
    private InternetConnection internetConnection = new InternetConnection();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewByIds();


        if (internetConnection.isNetworkAvailable(getApplicationContext())) {
            getDataForUrl();

        } else {
            Toast.makeText(getApplicationContext(), getResources().getString(R.string.internet_connection), Toast.LENGTH_SHORT).show();
        }
    }

    public  void  findViewByIds(){
        progressDialog=new ProgressDialog(MainActivity.this);
        textview_name= (TextView) findViewById(R.id.textview_name);
        textview_location= (TextView) findViewById(R.id.textview_location);
    }

    private void getDataForUrl() {

        String getDataForUrl = "getDataForUrl";

        progressDialog.setMessage(getResources().getString(R.string.please_wait));
        progressDialog.setCancelable(false);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();


        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
                getResources().getString(R.string.url_main), new JSONObject(),
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        System.out.println("response*******"+response);

                        try {
                             {

                                progressDialog.dismiss();

                                JSONArray jsonArrayUserArray = response.getJSONArray(Constant.results);
                                for(int i=0;i<jsonArrayUserArray.length();i++){
                                    JSONObject jsonObjectresults=jsonArrayUserArray.getJSONObject(i);
                                    String gender=jsonObjectresults.getString(Constant.gender);
                                    JSONObject jsonObjectname=jsonObjectresults.getJSONObject(Constant.name);
                                    String title=jsonObjectname.getString(Constant.title);
                                    String first=jsonObjectname.getString(Constant.first);
                                    String last=jsonObjectname.getString(Constant.last);
                                    System.out.println("first*******"+first);
                                    textview_name.setText(title+" "+first+" "+last);

                                    JSONObject jsonObjectlocation=jsonObjectresults.getJSONObject(Constant.location);
                                    String street=jsonObjectlocation.getString(Constant.street);
                                    String city=jsonObjectlocation.getString(Constant.city);
                                    String state=jsonObjectlocation.getString(Constant.state);

                                    textview_location.setText(street+" ,"+city+ " \n" +state);
                                    String email=jsonObjectresults.getString(Constant.email);



                                }





                            }
                        }catch (JSONException e){
                            progressDialog.dismiss();
                            System.out.println("response**e*****"+e);
                        }

                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {

                progressDialog.dismiss();

                if (error.networkResponse == null) {

                    if(error.getClass().equals(NoConnectionError.class)){
                        Toast.makeText(getApplicationContext(), R.string.timeout_error,
                                Toast.LENGTH_LONG).show();
                    }else if (error.getClass().equals(TimeoutError.class)) {
                        // Show timeout error message

                        Toast.makeText(getApplicationContext(), R.string.timeout_error,
                                Toast.LENGTH_LONG).show();

                    }
                }


            }
        }) {

            /**
             * Passing some request headers
             * */
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();

                return headers;
            }



        };

        // Adding request to request queue
        int socketTimeout = Constant.SocketTimeout;//60 seconds - change to what you want
        RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        jsonObjReq.setRetryPolicy(policy);
        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(jsonObjReq, getDataForUrl);

    }

AppController.class

package com.example.admin.volleylibrary;


import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.text.TextUtils;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;



public class AppController extends Application {


    public static final String TAG = AppController.class
            .getSimpleName();

    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;

    private static AppController mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized AppController getInstance() {
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    public ImageLoader getImageLoader() {
        getRequestQueue();
        if (mImageLoader == null) {
            mImageLoader = new ImageLoader(this.mRequestQueue,
                    new LruBitmapCache());
        }
        return this.mImageLoader;
    }

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        // set the default tag if tag is empty
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }




    // Notifies UI to display a message.
    public void displayRegistrationMessageOnScreen(Context context, String message) {

        Intent intent = new Intent(Config.DISPLAY_REGISTRATION_MESSAGE_ACTION);
        intent.putExtra(Config.EXTRA_MESSAGE, message);

        // Send Broadcast to Broadcast receiver with message
        context.sendBroadcast(intent);

    }

    private PowerManager.WakeLock wakeLock;

    public void acquireWakeLock(Context context) {
        if (wakeLock != null) wakeLock.release();

        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);

        wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |
                PowerManager.ACQUIRE_CAUSES_WAKEUP |
                PowerManager.ON_AFTER_RELEASE, "WakeLock");

        wakeLock.acquire();
    }

    public void releaseWakeLock() {
        if (wakeLock != null) wakeLock.release();
        wakeLock = null;
    }
}


Config.java

package com.example.admin.volleylibrary;
 
       public interface Config {

        static final boolean SECOND_SIMULATOR = false;

        // Google project id
        static final String GOOGLE_SENDER_ID = "417541187287";
     
        /**
         * Tag used on log messages.
         */
        static final String TAG = "GCM Android Example";
     
        // Broadcast reciever name to show gcm registration messages on screen 
        static final String DISPLAY_REGISTRATION_MESSAGE_ACTION =
                "com.tradeforsure.DISPLAY_REGISTRATION_MESSAGE";
         
        // Broadcast reciever name to show user messages on screen
        static final String DISPLAY_MESSAGE_ACTION =
            "com.tradeforsure.DISPLAY_MESSAGE";
     
        // Parse server message with this name
        static final String EXTRA_MESSAGE = "message";
         
         
    }

LruBitmapCache

This class is required to handle image cache.

package com.example.admin.volleylibrary;

import android.graphics.Bitmap;
import android.util.LruCache;

import com.android.volley.toolbox.ImageLoader;


/**
 * Created by ganeshtikone on 08/01/16.
 */
public class LruBitmapCache extends LruCache<String,Bitmap> implements ImageLoader.ImageCache {



    public static int getDefaultLruCacheSize() {
        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        final int cacheSize = maxMemory / 8;

        return cacheSize;
    }

    /**
     * @param maxSize for caches that do not override {@link #sizeOf}, this is
     *                the maximum number of entries in the cache. For all other caches,
     *                this is the maximum sum of the sizes of the entries in this cache.
     */
    public LruBitmapCache(int maxSize) {
        super(maxSize);
    }

    public LruBitmapCache(){
        super(getDefaultLruCacheSize());
    }


    @Override
    protected int sizeOf(String key, Bitmap value) {
        return value.getRowBytes() * value.getHeight() / 1024;
    }

    @Override
    public Bitmap getBitmap(String url) {
        return get(url);
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        put(url, bitmap);
    }
}

InternertConnection.java

package com.example.admin.volleylibrary;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.os.Build;

/**
 * Created by Admin on 25-04-2017.
 */

public class InternetConnection {

    public boolean isNetworkAvailable(Context context) {

        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Network[] networks = connectivity.getAllNetworks();
            NetworkInfo networkInfo;
            for (Network mNetwork : networks) {
                networkInfo = connectivity.getNetworkInfo(mNetwork);
                if (networkInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
                    return true;
                }
            }
        } else {
            if (connectivity != null) {

                NetworkInfo[] info = connectivity.getAllNetworkInfo();

                if (info != null) {

                    for (int i = 0; i < info.length; i++) {

                        if (info[i].getState() == NetworkInfo.State.CONNECTED) {

                            return true;

                        }

                    }
                }
            }

        }

        return false;
    }

}

Constant.class

package com.example.admin.volleylibrary;

/**
 * Created by Admin on 09-08-2017.
 */

public class Constant {
    public static String status = "status";
    public static String message = "message";
    public static String Message = "Message";
    public static String status_400 = "400";
    public static String status_422 = "422";
    public static String status_200 = "200";
    public static String results="results";
    public static String gender="gender";
    public static String name="name";
    public static String title="title";
    public static String first="first";
    public static String last="last";
    public static String location="location";
    public static String email="email";
    public static String street="street";
    public static String city="city";
    public static String state="state";
    public static int SocketTimeout = 60000;
}

strings.xml

<resources>
    <string name="app_name">VolleyLibrary</string>
    <string name="please_wait">Please wait.</string>
    <string name="url_main">https://randomuser.me/api/</string>
    <string name="timeout_error">Oops!!! Connection Timeout.</string>
    <string name="internet_connection">Please check your internet connection.</string>
</resources>

Declare AppController and permissions in manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.admin.volleylibrary">


    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:name=".AppController"
        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>

Download Volley library and sample example:https://github.com/rohan5576/VolleyLibrary

 

Please follow and like us:
0
0

1 comments on “Android working with Volley Library.”

  1. Pingback: EditProfile using Volley Library – Androtech

Leave a Reply

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