JSONObjectRequest example using volley in Android

When I started android development first thing I was stuck on was calling webservice with volley. The solutions I found was based on string requests (using StringRequest class) but I wanted to use JSONObject as parameter so I searched a lot but didn’t find any helpful information for using JSONObject. Finally I found one thing that there is another class in volley named JSONObjectRequest and using this we can send JSONObject to webservice.

So here I am sharing sample code of calling JSON webservice using JSONObjectRequest in volley

1. First thing we have to do is prepare your JSONObject which you want to send in your web service request.

     JSONObject request = new JSONObject();
     try
     {
      request.put("Param1", "Value1");
      request.put("Param2", "Value2");
     }
     catch(Exception e)
     {
      e.printStackTrace();
}

2. Now prepare request to send this json object to your web service

           JsonObjectRequest strReq = new JsonObjectRequest(Request.Method.POST, "http://<your service URL>", request,
            new Response.Listener<JSONObject>() {
@Override

public void onResponse(JSONObject response) {
},
new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError error) {
}
});


3. After sending request we have to parse the web service response

            public void onResponse(JSONObject responseObj) {
                try {
                    // Parsing json object response
                    boolean error = responseObj.getBoolean("Error");
                    String message = responseObj.getString("Message");
if (!error) {
// parsing the user profile information
JSONArray users= responseObj.getJSONArray("Users");

//do what ever you want to do with your response

Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();

} else {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}

} catch (JSONException e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}

}


4. In case web service return any error, here is how we can handle that

            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}

 

Here is how the complete code will look like

import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.jsonobjectrequestsample.NewActivity;
import com.example.jsonobjectrequestsample.MyApplication;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
private void GetUsers() {
    
     JSONObject request = new JSONObject();
     try
     {
      request.put("Param1", "Value1");
      request.put("Param2", "Value2");
     }
     catch(Exception e)
     {
      e.printStackTrace();
}

JsonObjectRequest strReq = new JsonObjectRequest(Request.Method.POST, "http://<your service URL>", request,
new Response.Listener<JSONObject>() {

@Override

public void onResponse(JSONObject response) {
try {
// Parsing json object response
boolean error = responseObj.getBoolean("Error");
String message = responseObj.getString("Message");

if (!error) {
// parsing the user profile information
JSONArray users= responseObj.getJSONArray("Users");

//do what ever you want to do with your response

Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();

} else {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}

} catch (JSONException e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});

// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(strReq);
}

You will notice that I have used MyApplication class to get instance because I used singleton and user this class for getting instance.

Here is the code of MyApplication class

import android.app.Application;
import android.text.TextUtils;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

public class MyApplication extends Application {
public static final String TAG = MyApplication .class
.getSimpleName();

private RequestQueue mRequestQueue;

private static MyApplication mInstance;

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

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

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

return mRequestQueue;
}

public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
req.setRetryPolicy(
new DefaultRetryPolicy(
DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 10,
HERE IS HOW THE COMPLETE CODE WILL LOOK LIKE               -1,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
)
);
getRequestQueue().add(req);
}

public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
req.setRetryPolicy(
new DefaultRetryPolicy(
DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 10,
-1,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
)
);
getRequestQueue().add(req);
}

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

Leave a Reply

Your email address will not be published.