Volley Library in Android Get JSON from Server

Volley is an android library released by Google that can make your life easier when dealing with network operations. In this blog post I will mention the main features of the library and show a few example usages, in particular, how to make a request, how to download images, and how to use the cache.
So lets start our android volley tutorial. In this tutorial we will create a application to fetch JSON string from server. I have already done with the scripting part before. If you want to know the php part for this tutorial visit this link. So I have already created my URL from where I will get the JSON string. My URL is....

1. MainActivity.java

package com.tutorialsee.volleyexample;

import com.tutorialsee.volleyexample.AppController;
import com.android.volley.Request.Method;
import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONArray;
import org.json.JSONObject;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity  implements OnItemSelectedListener {
List<ItemDetails> itemList = new ArrayList<ItemDetails>();
GridView listview;
ItemListAdapter ap_adap;
Context context;
TextView ssd;
String flg="L";
//Save kk;
Parcelable state;
static LinearLayout Lookingfor;
@SuppressWarnings("unused")
private int visibleThreshold = 1;
private int current_page = 1;
@SuppressWarnings("unused")
private int previousTotalItemCount = 0;
@SuppressWarnings("unused")
private boolean loading = true;
@SuppressWarnings("unused")
private int startingPageIndex = 0;
static String value ;
String Title;
int Totalnew = 1;
private String TAG = MainActivity.class.getSimpleName();
private String tag_json_obj = "jobj_req";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.product_gried_activity);

context = this;
listview = (GridView)  findViewById(R.id.gridView1);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});

if(Network.isConnectionFast(context)){
//kk = new Save();
itemList.clear();
current_page = 1;
makeJsonObjReq();
listview.setOnScrollListener(new EndlessScrollListener() {
public void onLoadMore(int page, int totalItemsCount) {
if(current_page<=Totalnew){
current_page++;
makeJsonObjReq();
}
}
});
}else{
Toast toast = Toast.makeText(getApplicationContext(), "Please check your internet connection", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}



}


private void makeJsonObjReq() {
MyProgressDialog.show(context);
int Item = 32;
StringRequest jsonObjReq = new StringRequest(Method.GET,
Constant.SEG() + Item +"?current_page="+current_page, new Response.Listener<String>() {


@Override
public void onResponse(String response) {
Log.d("TAG", response);
if(response.length()>10){
try {


JSONArray jArray = new JSONArray(response.substring(response.indexOf("nid")-3)+"");

int number = jArray.length();
number = number - 1;
for (int i = 0; i < jArray.length(); i++) {

ItemDetails k = new ItemDetails();
JSONObject jObject = jArray.getJSONObject(i);
k.setNid(Long.parseLong((String) jObject.get("nid")));
k.setTitle(jObject.getString("title"));
String price = jObject.getString("price");
double f = Double.parseDouble(price);
k.setPrice(String.format("%.2f", new BigDecimal(f)));
k.setThumb_Images(((String) jObject.get("thumb_images")));

itemList.add(k);
}

}
catch (Exception e) {
}
}


MyProgressDialog.close(context);
if(itemList.size() == 0){  

}else{
ap_adap = new ItemListAdapter(context,R.layout.product_grid, itemList);
state = listview.onSaveInstanceState();
listview.setAdapter(ap_adap);
listview.onRestoreInstanceState(state);
}
}


}, new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
MyProgressDialog.close(context);
}
}) {

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}

@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("name", "Tutorialsee");
params.put("email", "info@tutorialsee.com");
params.put("pass", "password123");

return params;
}
};

// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq,tag_json_obj);
}


@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
}

@Override
public void onNothingSelected(AdapterView<?> parent) {
}

/**
* Making json object request
* *//*
private void makeJsonObjReq() {
showProgressDialog();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
Const.URL_JSON_OBJECT, null,
new Response.Listener<JSONObject>() {

@Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideProgressDialog();
}
}) {

*//**
* Passing some request headers
* *//*
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
return headers;
}

@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("name", "Androidhive");
params.put("email", "abc@androidhive.info");
params.put("pass", "password123");

return params;
}

};

// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq,
tag_json_obj);

// Cancelling request
// ApplicationController.getInstance().getRequestQueue().cancelAll(tag_json_obj);
}

*//**
* Making json array request
* *//*
private void makeJsonArryReq() {
showProgressDialog();
JsonArrayRequest req = new JsonArrayRequest(Const.URL_JSON_ARRAY,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideProgressDialog();
}
});

// Adding request to request queue
AppController.getInstance().addToRequestQueue(req,
tag_json_arry);

// Cancelling request
// ApplicationController.getInstance().getRequestQueue().cancelAll(tag_json_arry);
}
*/

}

2. AppController.java

package com.tutorialsee.volleyexample;

import com.tutorialsee.volleyexample.LruBitmapCache;
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);
}
}
}

3. LruBitmapCache.java

package com.tutorialsee.volleyexample;

import com.android.volley.toolbox.ImageLoader.ImageCache;

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

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);
}
}