Skip to content

Instantly share code, notes, and snippets.

@hitraj47
Last active May 2, 2021 13:56
Show Gist options
  • Save hitraj47/e51cb29a7781704a4766 to your computer and use it in GitHub Desktop.
Save hitraj47/e51cb29a7781704a4766 to your computer and use it in GitHub Desktop.
[Tutorial] Using Volley with Android Studio

Volley, Android Studio and Examples

This tutorial is really just some code snippets to show you how to use Volley in Android Studio for your Android project. The tutorial will show you how you can import Volley, an example of retrieving a JSON object and retrieving an image for use in a layout.

Files and Code Snippets

The code snippets that are references should be listed below, after this readme file.

Importing Volley into Android Studio

To import Volley into your project, you have to use a 3rd party mirror or the Volley library. However, it is only 1 line of code. Open your app/build.gradle and add the following dependency:

compile 'com.mcxiaoke.volley:library:1.0.+@aar'

Required Classes

The first class you will need is a singleton that handles Volley requests. See the AppController code snippet.

Second, you will need an image cache, see the LruBitmapCache code snippet.

Getting a JSON Object or JSON Array

To retrieve a JSON Object, see the code example.

  • The code is very similar for JSON arrays
  • The TAG variable is just used for Logcat - the response is being made into a string and output into the Logcat console.
  • onReponse is where you would do what you need with the returned data

Displaying an Image in NetworkImageView

To display an image, in your layout, you will need a NetworkImageView. This is similar to an ImageView. See the NetworkImageView XML example.

The code to display an image in the NetworkImageView is:

NetworkImageView imageView = (NetworkImageView) findViewById(R.id.image); imageView.setImageUrl("http://www.website.com/path/to/image.jpg", AppController.getInstance().getImageLoader());

If you would like to set placeholder and error images, see the Placeholder and Error Images code sample.

import android.app.Application;
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);
}
}
}
// Tag used to cancel the request
String tag_json_obj = "json_obj_req";
String url = "http://www.api.com/your/api/request";
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
pDialog.hide();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
// hide the progress dialog
pDialog.hide();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import com.android.volley.toolbox.ImageLoader.ImageCache;
public class LruBitmapCache extends LruCache<String, Bitmap> implements
ImageCache {
public static int getDefaultLruCacheSize() {
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
return cacheSize;
}
public LruBitmapCache() {
this(getDefaultLruCacheSize());
}
public LruBitmapCache(int sizeInKiloBytes) {
super(sizeInKiloBytes);
}
@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);
}
}
<com.android.volley.toolbox.NetworkImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
NetworkImageView imageView = (NetworkImageView) findViewById(R.id.image);
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
imageLoader.get("http://www.website.com/path/to/image.jpg", ImageLoader.getImageListener(imageView, R.drawable.ico_loading, R.drawable.ico_error));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment