Android Volley framework how to unit test - android

I use the volley framework for my controllers in an android application
One of my controllers is as below:
public class LoginApi extends AppCompatActivity {
private static final String LOGIN_URL = "example"
private static final int timeOutInMs = 10000;
private static final int numberOfTries = 1;
public LoginApi() {
}
public void doLogin(final Context context, JSONObject jsonObject) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, LOGIN_URL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
User user=new User();
try {
user.setAccessToken(response.getString("access_token"));
user.setExpireToken(response.getString("expires_in"));
user.setRefreshToken(response.getString("refresh_token"));
user.setTokenType(response.getString("token_type"));
Intent intent=new Intent(context,MenuCustomer.class);
Gson myGson=new Gson();
String myJson = myGson.toJson(user);
intent.putExtra("myjson", myJson);
context.startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("", "");
Toast.makeText(context, "Successfull login", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("", "");
Toast.makeText(context, "Please enter a valid email and password", Toast.LENGTH_SHORT).show();
}
}) {
#Override
public Map<String, String> getHeaders() {
Map<String, String> map = new HashMap<>();
map.put("Accept", "application/json");
map.put("Content-Type", "application/json");
return map;
}
};
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(timeOutInMs, numberOfTries, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Singleton.getmInstance(context).addToRequestQueue(jsonObjectRequest);
}
}
I have tried to make mock classes (FakeHttpStack,FakeRequestQueue) and I tried to make tests from mock volley classes from here
I cant find a solution to unit test my class.

Related

Return response of Volley of Android [duplicate]

This question already has answers here:
Can I do a synchronous request with volley?
(8 answers)
Closed 4 years ago.
I have written a function that makes an HTTP request and the response stores in a Bundle to subsequently initialize an activity.
public static void communicate(final Context context, String url, final String typeResponse, final Intent intent) {
RequestQueue queue = Volley.newRequestQueue(context);
RequestFuture<String> future = RequestFuture.newFuture();
StringRequest stringRequest = new StringRequest(Request.Method.POST, BASE_URL + url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Toast.makeText(context, response, Toast.LENGTH_SHORT).show();
Bundle bundle = new Bundle();
switch (typeResponse) {
case "text":
bundle.putString("response", response);
break;
case "json":
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray names = jsonObject.names();
for (int i = 0; i < names.length(); i++) {
//Toast.makeText(context, names.getString(i), Toast.LENGTH_SHORT).show();
bundle.putString(names.getString(i), jsonObject.getString(names.getString(i)));
}
} catch (JSONException e) {
e.printStackTrace();
}
break;
}
intent.putExtras(bundle);
context.startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "error", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("test", "hi!!");
return params;
}
};
queue.add(stringRequest);
}
But I want return the Bundle object for use that function like this:
Bundle myBundle = communicate('httl://qwe.asd', 'json')
How can I to modifier my function?
Thanks.
Volley request are asynchronous, so i recommend you put inner your onResponse other function to be process your bundle.
As well, you can create an interface to send your response in other place. Something like this
interface
public interface onResponseCallback {
void onResponse(Bundle bundle);
}
activity
public MyActivity extends AppCompatActivity implements onResponseCallback{
public void onCreate(Bundle....){
MyRequest myrequest = new MyRequest(this);
..}
public void onResponse(Bundle bundle){
//bundle argument is your response from request,
// do some with your response
Intent intent = new Intent....
intent.putExtras(bundle);
startActivity(intent);
}
}
Request class
public class MyRequest{
OnResponseCallback onResponseCallback= null;
public MyRequest(onResponseCallback onResponseCallback)
this.onResponseCallback = onResponseCallback;
}
public void communicate(final Context context, String url, final String typeResponse, final Intent intent) {
RequestQueue queue = Volley.newRequestQueue(context);
RequestFuture<String> future = RequestFuture.newFuture();
StringRequest stringRequest = new StringRequest(Request.Method.POST, BASE_URL + url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Toast.makeText(context, response, Toast.LENGTH_SHORT).show();
Bundle bundle = new Bundle();
switch (typeResponse) {
case "text":
bundle.putString("response", response);
break;
case "json":
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray names = jsonObject.names();
for (int i = 0; i < names.length(); i++) {
//Toast.makeText(context, names.getString(i), Toast.LENGTH_SHORT).show();
bundle.putString(names.getString(i), jsonObject.getString(names.getString(i)));
}
} catch (JSONException e) {
e.printStackTrace();
}
break;
}
onResponseCallback.onResponse(bundle);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "error", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("test", "hi!!");
return params;
}
};
queue.add(stringRequest);
}
}
and if you dont like nothing of this, maybe you can use constants or put in sharedpreferences to save your bundle object.
I hope that helps you.

Handle Multiple request in Android volley

I am trying to hit multiple request using Volley and i am getting response for all the request. my problem is how to identify the response is belong to which API.
mQueue = CustomVolleyRequest.getInstance(this.getApplicationContext())
.getRequestQueue();
final CustomJSONObjectrequest jsonRequest = new CustomJSONObjectrequest(Request.Method
.GET, url,
new JSONObject(), this, this); //
jsonRequest.setTag(REQUEST_TAG);
final CustomJSONObjectrequest jsonRequest2 = new CustomJSONObjectrequest(Request.Method
.GET, url2,
new JSONObject(), this, this);
jsonRequest2.setTag(REQUEST_TAG);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mQueue.add(jsonRequest);
mQueue.add(jsonRequest2); // Both the request will have different API request
}
});
}
#Override
public void onErrorResponse(VolleyError error) {
mTextView.setText(error.getMessage());
}
#Override
public void onResponse(Object response) {
// How to identify, which response is belong to which api request
mTextView.setText("Response is: " + response);
}
Create a Generic Volley class and a Interface, Use the interface to get success and failure responds.
Step 1 Create a separate Volley class
Step 2 Create a interface for accessing the response from volley class
Step 3 create new object for
the class and send required parameters
new PostVolleyJsonRequest(TestVolley.this, TestVolley.this(interfcae), "Submit", url, params);
Context of the class
Interface for sending Success and failure responds
Type of request to identify on success
url (mandatory)
Param (optional) for GET no need
Generic volley class
public class PostVolleyJsonRequest {
private String type;
private Activity act;
private VolleyJsonRespondsListener volleyJsonRespondsListener;
private String networkurl;
private JSONObject jsonObject = null;
private JSONObject params;
public PostVolleyJsonRequest(Activity act, VolleyJsonRespondsListener volleyJsonRespondsListener, String type, String netnetworkUrl,JSONObject params) {
this.act = act;
this.volleyJsonRespondsListener = volleyJsonRespondsListener;
this.type = type;
this.networkurl = netnetworkUrl;
this.params = params;
sendRequest();
}
private void sendRequest() {
Log.d("url", "url" + networkurl);
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,networkurl,params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("response", "response " + response);
volleyJsonRespondsListener.onSuccessJson(response, type);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
try {
NetworkResponse response = error.networkResponse;
Log.e("response", "response " + response);
if (response != null) {
int code = response.statusCode;
String errorMsg = new String(response.data);
Log.e("response", "response" + errorMsg);
try {
jsonObject = new JSONObject(errorMsg);
} catch (JSONException e) {
e.printStackTrace();
}
String msg = jsonObject.optString("message");
volleyJsonRespondsListener.onFailureJson(code, msg);
} else {
String errorMsg = error.getMessage();
volleyJsonRespondsListener.onFailureJson(0, errorMsg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
jsObjRequest.setRetryPolicy(new DefaultRetryPolicy(
600000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestqueue = Volley.newRequestQueue(act);
requestqueue.add(jsObjRequest);
}
}
Use the interface to get responds message
public interface VolleyJsonRespondsListener {
public void onSuccessJson(JSONObject result, String type);
public void onFailureJson(int responseCode, String responseMessage);
}
In your class where you want to include multiple request
public class TestVolley extends AppCompatActivity implements VolleyJsonRespondsListener{
//Your class code goes here
//network request
try {
//parameters
//Context,Interface,Type(to indentify your responds),URL,parameter for your request
//request 1
new PostVolleyJsonRequest(TestVolley.this, TestVolley.this, "Submit", url, params);
//request 2
new PostVolleyJsonRequest(TestVolley.this, TestVolley.this, "AccessData", url_2, params_2);
} catch (Exception e) {
e.printStackTrace()
}
//Methods from Interface
#Override
public void onSuccessJson(JSONObject result, String type) {
//Based on the Type you send get the responds and parse it
switch (type) {
case "Submit":
try {
parseSubmit(result);
} catch (Exception e) {
e.printStackTrace();
}
break;
case "AccessData":
try {
parseAccessData(result);
} catch (Exception e) {
e.printStackTrace();
}
break;
}
You can do something like this for a single request. Same can be applied to the second request. This way you know which request is giving you the response.
final CustomJSONObjectrequest jsonRequest = new CustomJSONObjectrequest(Request.Method
.GET, url,
new JSONObject(), this, new Response.Listener<Object>() {
#Override
public void onResponse(Object response) {
// How to identify, which response is belong to which api request
mTextView.setText("Response is: " + response);
});
EDITED :
You can start with making an interface like :
public interface VolleyResponse {
void onResponse(JSONObject object, String tag);
void onError(VolleyError error, String tag);
}
Then you can make a custom handler for volley request like:
public class CustomJSONObjectRequest implements Response.Listener<JSONObject>, Response.ErrorListener {
private VolleyResponse volleyResponse;
private String tag;
private JsonObjectRequest jsonObjectRequest;
public CustomJSONObjectRequest(int method, String url, JSONObject jsonObject, String tag, VolleyResponse volleyResponse) {
this.volleyResponse = volleyResponse;
this.tag= tag;
jsonObjectRequest = new JsonObjectRequest(method, url, jsonObject, this, this);
}
#Override
public void onResponse(JSONObject response) {
volleyResponse.onResponse(response, tag);
}
#Override
public void onErrorResponse(VolleyError error) {
volleyResponse.onError(error, tag);
}
public JsonObjectRequest getJsonObjectRequest() {
return jsonObjectRequest;
}
}
And to call it in your class use it like:
CustomJSONObjectRequest request1 = new CustomJSONObjectRequest(Request.Method.GET, url,
new JSONObject(), "YOUR REQUEST TAG", this);
Make sure to let your class implement the VolleyResponse interface that will get you the response and your tag.
#Override
public void onResponse(JSONObject object, String tag) {
Log.i("Response :", object.toString() + " " + tag);
}
#Override
public void onError(VolleyError error, String tag) {
}
To add the request to the volley queue you can use:
mQueue.add(request1.getJsonObjectRequest());
PS : this code is not tested but it should work.

How to make separate class for volley library and call all method of volley from another activity and get response?

how to create a separate class in which define all about volley
and in another activity we directly pass URL,CONTEXT and Get Response...
First create callback interface to get result in Activity
public interface IResult {
public void notifySuccess(String requestType,JSONObject response);
public void notifyError(String requestType,VolleyError error);
}
Create a separate class with volley function to response the result through interface to activity
public class VolleyService {
IResult mResultCallback = null;
Context mContext;
VolleyService(IResult resultCallback, Context context){
mResultCallback = resultCallback;
mContext = context;
}
public void postDataVolley(final String requestType, String url,JSONObject sendObj){
try {
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObj = new JsonObjectRequest(url,sendObj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if(mResultCallback != null)
mResultCallback.notifySuccess(requestType,response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null)
mResultCallback.notifyError(requestType,error);
}
});
queue.add(jsonObj);
}catch(Exception e){
}
}
public void getDataVolley(final String requestType, String url){
try {
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObj = new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if(mResultCallback != null)
mResultCallback.notifySuccess(requestType, response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null)
mResultCallback.notifyError(requestType, error);
}
});
queue.add(jsonObj);
}catch(Exception e){
}
}
}
Then initialize callback interface into main activity
mResultCallback = new IResult() {
#Override
public void notifySuccess(String requestType,JSONObject response) {
Log.d(TAG, "Volley requester " + requestType);
Log.d(TAG, "Volley JSON post" + response);
}
#Override
public void notifyError(String requestType,VolleyError error) {
Log.d(TAG, "Volley requester " + requestType);
Log.d(TAG, "Volley JSON post" + "That didn't work!");
}
};
Now create object of VolleyService class and pass it context and callback interface
mVolleyService = new VolleyService(mResultCallback,this);
Now call the Volley method for post or get data also pass requestType which is to identify the service requester when getting result back into main activity
mVolleyService.getDataVolley("GETCALL","http://192.168.1.150/datatest/get/data");
JSONObject sendObj = null;
try {
sendObj = new JSONObject("{'Test':'Test'}");
} catch (JSONException e) {
e.printStackTrace();
}
mVolleyService.postDataVolley("POSTCALL", "http://192.168.1.150/datatest/post/data", sendObj);
Final MainActivity
public class MainActivity extends AppCompatActivity {
private String TAG = "MainActivity";
IResult mResultCallback = null;
VolleyService mVolleyService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initVolleyCallback();
mVolleyService = new VolleyService(mResultCallback,this);
mVolleyService.getDataVolley("GETCALL","http://192.168.1.150/datatest/get/data");
JSONObject sendObj = null;
try {
sendObj = new JSONObject("{'Test':'Test'}");
} catch (JSONException e) {
e.printStackTrace();
}
mVolleyService.postDataVolley("POSTCALL", "http://192.168.1.150/datatest/post/data", sendObj);
}
void initVolleyCallback(){
mResultCallback = new IResult() {
#Override
public void notifySuccess(String requestType,JSONObject response) {
Log.d(TAG, "Volley requester " + requestType);
Log.d(TAG, "Volley JSON post" + response);
}
#Override
public void notifyError(String requestType,VolleyError error) {
Log.d(TAG, "Volley requester " + requestType);
Log.d(TAG, "Volley JSON post" + "That didn't work!");
}
};
}
}
Find the whole project at following link
https://github.com/PatilRohit/VolleyCallback
JsonParserVolley.java
(A separate class where we will get the response)
public class JsonParserVolley {
final String contentType = "application/json; charset=utf-8";
String JsonURL = "Your URL";
Context context;
RequestQueue requestQueue;
String jsonresponse;
private Map<String, String> header;
public JsonParserVolley(Context context) {
this.context = context;
requestQueue = Volley.newRequestQueue(context);
header = new HashMap<>();
}
public void addHeader(String key, String value) {
header.put(key, value);
}
public void executeRequest(int method, final VolleyCallback callback) {
StringRequest stringRequest = new StringRequest(method, JsonURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
jsonresponse = response;
Log.e("RES", " res::" + jsonresponse);
callback.getResponse(jsonresponse);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return header;
}
}
;
requestQueue.add(stringRequest);
}
public interface VolleyCallback
{
public void getResponse(String response);
}
}
MainActivity.java
(Code Snippet written in onCreate method)
final JsonParserVolley jsonParserVolley = new JsonParserVolley(this);
jsonParserVolley.addHeader("Authorization", "Your value");
jsonParserVolley.executeRequest(Request.Method.GET, new JsonParserVolley.VolleyCallback() {
#Override
public void getResponse(String response) {
jObject=response;
Log.d("VOLLEY","RES"+jObject);
parser();
}
}
);
parser() is the method where the json response obtained is used to bind with the components of the activity.
you actually missed one parameter in the above VolleyService class. You needed to include, it is,...
JsonObjectRequest jsonObj = new JsonObjectRequest(Request.Method.GET, url,null,new Response.Listener() {
/..../
}
null is the parameter should be included else it gives error
Create Listeners(since they are interface they can't be instantiated but they can be instantied as an anonymous class that implement interface) inside the activity or fragment. And Pass this instances as parameters to the Request.(StringRequest, JsonObjectRequest, or ImageRequest).
public class MainActivity extends Activity {
private static final String URI = "";
// This is like BroadcastReceiver instantiation
private Listener<JSONObject> listenerResponse = new Listener<JSONObject>() {
#Override
public void onResponse(JSONObject arg0) {
// Do what you want with response
}
};
private ErrorListener listenerError = new ErrorListener() {
#Override
public void onErrorResponse(VolleyError arg0) {
// Do what you want with error
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Next, create a class that has request and pass this listeners to this class' request method , that's all. I don't explain this part this is same as creating a request object in any tutorials.But you can customize this class as you wish. You can create singleton RequestQueue to check priority, or set body http body parameters to this methods as paremeters.
public class NetworkHandler {
public static void requestJSON(Context context, String url, Listener<JSONObject> listenerResponse, ErrorListener listenerError) {
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, url, null, listenerResponse, listenerError);
Volley.newRequestQueue(context).add(jsonRequest);
}
}
public class VolleyService {
IResult mResultCallback = null;
Context mContext;
VolleyService(IResult resultCallback, Context context)
{
mResultCallback = resultCallback;
mContext = context;
}
//--Post-Api---
public void postDataVolley(String url,final Map<String,String> param){
try {
StringRequest sr = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(mResultCallback != null)
mResultCallback.notifySuccessPost(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null)
mResultCallback.notifyError(error);
}
}) {
#Override
protected Map<String, String> getParams() {
return param;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
AppController.getInstance(mContext).addToRequestQueue(sr);
}catch(Exception e){
}
}
//==Patch-Api==
public void patchDataVolley(String url,final HashMap<String,Object> param)
{
JsonObjectRequest request = new JsonObjectRequest(Request.Method.PATCH, url, new JSONObject(param),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if(mResultCallback != null)
mResultCallback.notifySuccessPatch(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null)
mResultCallback.notifyError(error);
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
return headers;
}
};
AppController.getInstance(mContext).addToRequestQueue(request);
}
}
public interface IResult {
void notifySuccessPost(String response);
void notifySuccessPatch(JSONObject jsonObject);
void notifyError(VolleyError error);
}

Volley Post Request in Android

I am using Volley to post some data in a server.
private void checkLeague(final String username, final String password) {
String tag_json_obj = "json_obj_req";
final HashMap<String, String> postParams = new HashMap<String, String>();
postParams.put("username", username);
postParams.put("password", password);
Response.Listener<JSONObject> listener;
Response.ErrorListener errorListener;
final JSONObject jsonObject = new JSONObject(postParams);
final JsonObjectRequest jsonObjReq = new JsonObjectRequest(AppConfig.URL_CHECK_LEAGUE, jsonObject,
new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
if (response.getString("status").equals("fail")) {
checkLeader(username,password);
} else if (response.getString("status").equals("success")) {
deleteSharedPreferences();
text.setText("");
//timer.setText("League starts in:");
leagueCreation.setVisibility(View.GONE);
leagueInvitation.setVisibility(View.VISIBLE);
listView.setVisibility(View.VISIBLE);
readCheckLeagueSuccessfullData(response);
compareLeader();
dateFormatter();
setLeagueName();
getLeagueMembers(leagueId, username, password);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Bundle b = new Bundle();
b.putString("team_name", teamName);
b.putString("team_leader", teamLeader);
Intent intent = new Intent(League.this, UserDetails.class);
intent.putExtra("players_bundle", b);
startActivity(intent);
}
});
leagueInvitation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(League.this, LeagueInvitation.class);
i.putExtra("leagueId", leagueId);
i.putExtra("leagueName", leagueNameDb);
startActivity(i);
}
});
CounterClass counter = new CounterClass(leagueStartDiff, 1000);
counterTwoWeeks = new CounterClass1(leagueTwoWeeks, 1000);
counter.start();
}
} catch (JSONException e) {
Log.e("TAG", e.toString());
}
//pDialog.dismiss();
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//VolleyLog.d("TAG", "Error: " + error.getMessage());
//pDialog.dismiss();
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq,
tag_json_obj);
VolleySingleton.getInstance(getApplicationContext()).
addToRequestQueue(jsonObjRequest);
}
I put a breakpoint in this line
final JsonObjectRequest jsonObjReq = ...
to check if the data username,password in this case are basically going to the server. The problem is that I get this response which I don't like it very much.
[ ] http://.../..._..._check.php 0x8237d9fb NORMAL null
I should had got something like this from the debugger for the post request.
{
"username":"...",
"password":"..."
}
But I don't know why I get the null thing in my json request! It was working fine before. Maybe the link is broken?
Thank you.

How do you use the Android Volley API?

I am thinking of implementing the Android Volley library in my next projects (Google IO presentation about Volley).
However, I haven't found any serious API for that library.
How do I upload files, do POST/GET requests, and add a Gson parser as a JSON parser using Volley?
Source code
Edit: finally here it is an official training about "Volley library"
I found some examples about Volley library
6 examples by Ognyan Bankov :
Simple request
JSON request
Gson request
Image loading
with newer external HttpClient (4.2.3)
With Self-Signed SSL Certificate.
one good simple example by Paresh Mayani
other example by Hardik Trivedi
(NEW) Android working with Volley Library by Ravi Tamada
Unfortunately there is no documentation for a Volley library like JavaDocs until now. Only repo on github and several tutorials across the Internet. So the only good docs is source code :) . When I played with Volley I read this tutorial.
About post/get you can read this : Volley - POST/GET parameters Hope this helps
This is an illustration for making a POST request using Volley. StringRequest is used to get response in the form of String.
Assuming your rest API returns a JSON. The JSON response from your API is received as String here, which you can covert again to JSON and process it further. Added comments in code.
StringRequest postRequest = new StringRequest(Request.Method.POST, "PUT_YOUR_REST_API_URL_HERE",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
final JSONObject jsonObject = new JSONObject(response);
// Process your json here as required
} catch (JSONException e) {
// Handle json exception as needed
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
String json = null;
NetworkResponse response = error.networkResponse;
if(response != null && response.data != null){
switch(response.statusCode) {
default:
String value = null;
try {
// It is important to put UTF-8 to receive proper data else you will get byte[] parsing error.
value = new String(response.data, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
json = trimMessage(value, "message");
// Use it for displaying error message to user
break;
}
}
loginError(json);
progressDialog.dismiss();
error.printStackTrace();
}
public String trimMessage(String json, String key){
String trimmedString = null;
try{
JSONObject obj = new JSONObject(json);
trimmedString = obj.getString(key);
} catch(JSONException e){
e.printStackTrace();
return null;
}
return trimmedString;
}
}
) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("abc", "pass abc");
params.put("xyz", "pass xyz");
// Pass more params as needed in your rest API
// Example you may want to pass user input from EditText as a parameter
// editText.getText().toString().trim()
return params;
}
#Override
public String getBodyContentType() {
// This is where you specify the content type
return "application/x-www-form-urlencoded; charset=UTF-8";
}
};
// This adds the request to the request queue
MySingleton.getInstance(YourActivity.this)
.addToRequestQueue(postRequest);
// Below is MySingleton class
public class MySingleton {
private static MySingleton mInstance;
private RequestQueue mRequestQueue;
private static Context mCtx;
private MySingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
}
public static synchronized MySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new MySingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
}
Just add volley.jar library to your project.
and then
As per Android documentation :
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// process your response here
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//perform operation here after getting error
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
For more help refer How to user Volley
In simple way
private void load() {
JsonArrayRequest arrayreq = new JsonArrayRequest(ip.ip+"loadcollege.php",
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Album a;
try {
JSONArray data = new JSONArray(response.toString());
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
one = c.getString("cname").split(",");
two=c.getString("caddress").split(",");
three = c.getString("image").split(",");
four = c.getString("cid").split(",");
five = c.getString("logo").split(",");
a = new Album(one[0].toString(),two[0].toString(),ip.ip+"images/"+ three[0].toString(),four[0].toString(),ip.ip+"images/"+ five[0].toString());
albumList.add(a);
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
// The final parameter overrides the method onErrorResponse() and passes VolleyError
//as a parameter
new Response.ErrorListener() {
#Override
// Handles errors that occur due to Volley
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
}
);
// Adds the JSON array request "arrayreq" to the request queue
requestQueue.add(arrayreq);
}
Before testing all of the above answers, include
compile 'com.android.volley:volley:1.0.0'
in your gradle file and don't forgot to add the Internet permission to your Manifest file.
Use this class. It provides you an easy way to connect to the database.
public class WebRequest {
private Context mContext;
private String mUrl;
private int mMethod;
private VolleyListener mVolleyListener;
public WebRequest(Context context) {
mContext = context;
}
public WebRequest setURL(String url) {
mUrl = url;
return this;
}
public WebRequest setMethod(int method) {
mMethod = method;
return this;
}
public WebRequest readFromURL() {
RequestQueue requestQueue = Volley.newRequestQueue(mContext);
StringRequest stringRequest = new StringRequest(mMethod, mUrl, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
mVolleyListener.onRecieve(s);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
mVolleyListener.onFail(volleyError);
}
});
requestQueue.add(stringRequest);
return this;
}
public WebRequest onListener(VolleyListener volleyListener) {
mVolleyListener = volleyListener;
return this;
}
public interface VolleyListener {
public void onRecieve(String data);
public void onFail(VolleyError volleyError);
}
}
Example usage:
new WebRequest(mContext)
.setURL("http://google.com")
.setMethod(Request.Method.POST)
.readFromURL()
.onListener(new WebRequest.VolleyListener() {
#Override
public void onRecieve(String data) {
}
#Override
public void onFail(VolleyError volleyError) {
}
});
private void userregister() {
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
RequestQueue queue = Volley.newRequestQueue(SignupActivity.this);
String url = "you";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pDialog.cancel();
try {
JSONObject jsonObject= new JSONObject(response.toString());
Log.e("status", ""+jsonObject.getString("status"));
if(jsonObject.getString("status").equals("success"))
{
String studentid=jsonObject.getString("id");
Intent intent=new Intent(SignupActivity.this, OTPVerificationActivity.class);
startActivity(intent);
finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("String ", ""+response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("password", input_password.getText().toString());
params.put("cpassword", input_reEnterPassword.getText().toString());
params.put("email", input_email.getText().toString());
params.put("status", "1");
params.put("last_name", input_lastname.getText().toString());
params.put("phone", input_mobile.getText().toString());
params.put("standard", input_reStandard.getText().toString());
params.put("first_name", input_name.getText().toString());
params.put("refcode", input_reReferal.getText().toString());
params.put("created_at","");
params.put("update_at", "");
params.put("address", input_address.getText().toString());
return params;
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
Get full code here

Categories

Resources