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.
Related
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.
This is my Arraylist which I get from the previous fragment,
listoftags = getArguments().getParcelableArrayList("data");
It works well. Now I have to send this with some parameters like below:
public void volleyJsonObjectRequest(final String SessionID , final String CustomerID, final String ServiceState , final String ServiceID, final String Address, final String PaymentMode, final String CustomerComments , final ArrayList Items){
String REQUEST_TAG = "volleyJsonObjectRequest";
// POST parameters
CustomRequest request = new CustomRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Toast.makeText(SignActivity.this, response.toString(), Toast.LENGTH_SHORT).show();
Log.d("response",""+response.toString());
/* String status = response.optString("StatusMessage");
String actionstatus = response.optString("ActionStatus");
Toast.makeText(getActivity(), ""+status, Toast.LENGTH_SHORT).show();
if(actionstatus.equals("Success"))
{
// Intent i = new Intent(SignActivity.this, LoginActivity.class);
// startActivity(i);
// finish();
}*/
dismissProgress();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Error."+error.toString(), Toast.LENGTH_SHORT).show();
Log.d("response",""+error.toString());
dismissProgress();
}
}) {
/* #Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}*/
public String getBodyContentType()
{
return "application/json; charset=utf-8";
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
JSONArray jsArray = new JSONArray(listoftags);
params.put("SessionID", SessionID);
params.put("CustomerID", CustomerID);
params.put("ServiceState", ServiceState);
params.put("ServiceID", ServiceID);
params.put("Address", Address);
params.put("PaymentMode",PaymentMode);
params.put("CustomerComments",CustomerComments);
params.put("Items",jsArray.toString());
return params;
}
};
AppSingleton.getInstance(getActivity().getApplicationContext())
.addToRequestQueue(request, REQUEST_TAG);
}
but it getting error to me I want to send it like
// server side //
{
"SessionID":"9lm5255sg0ti9",
"CustomerID":"9",
"ServiceState":"Karnataka",
"ServiceID":"3",
"Address":"sfaff",
"PaymentMode":"cash",
"CustomerComments":"this is fine",
"Items":[
{
"ItemId":1,
"Cost":6777,
"Quantity":33333
}
]
}
How can send arraylist, with other strings, as raw data using volley on server.
JsonObjectRequest can be used to execute rest api using json as input.
JsonObject jobj = new JsonObject();
jobj.put("key","value");
jobj.put("key","value");
jobj.put("key","value");
jobj.put("key","value");
JsonObjectRequest request = new JsonObjectRequest(requestURL, jobj, new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
}
});
*Now add this request in request queue of volley.*
Here jobj is containing input parameters. It can contain even json array inside a JsonObject. Let me know in case of any query.
Rather then volley try retrofit. Make pojo model of your object you want to send, you can make that from pojo classes from https://www.jsonschema2pojo.org the send the whole object on restapi
// try the request //
try {
REQUEST QUEUE
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
String URL = url;
JSONObject jsonBody = new JSONObject();
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
Iterator itr = listoftags.iterator();
while(itr.hasNext()){
AddRowItem ad=(AddRowItem)itr.next();
jsonObject.put("ItemId:",1);
jsonObject.put("Cost:",ad.getPrices());
jsonObject.put("Quantity:",ad.getQty());
// Log.d("ItemId:",""+1+" "+"Cost:"+ad.getPrices()+" "+"Quantity:"+ad.getQty());
}
jsonArray.put(jsonObject);
JSON VALUES PUT
jsonBody.put("SessionID", "9kp0851kh6mk3");
jsonBody.put("CustomerID", "9");
jsonBody.put("ServiceState", "Karnataka");
jsonBody.put("ServiceID", "3");
jsonBody.put("Address", "Address Demo");
jsonBody.put("PaymentMode", "cost");
jsonBody.put("CustomerComments", "Android Volley Demo");
jsonBody.put("Items", jsonArray);
final String requestBody = jsonBody.toString();
Log.d("string ---- >",""+requestBody);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
showToast("get value"+response.toString());
try {
JSONObject jObj = new JSONObject(response);
String action = jObj.get("ActionStatus").toString();
String status = jObj.getString("StatusMessage");
{"ActionStatus":"Success","StatusMessage":"Order Created","RefIDName":"OrderID","RefIDValue":19}
showToast("get value"+action);
}
catch (JSONException e)
{
showToast("get error"+e.toString());
Log.d("errorissue",""+e.toString());
}
dismissProgress();
}
}, new Response.ErrorListener() {
// error response //
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
showToast("get error"+error.toString());
dismissProgress();
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
dismissProgress();
}
}
}
// THIS IS THE WAY ISSUE RESLOVED //
THANKS EVERYONE ...
I get an error when I make multiple volley requests.
First, I am requesting login and it works fine. After the login process, the main activity opens in the application. When I make a new request here, the request is added to the queue. But the request is not executed. what is the reason of this?
This code is login function:
private void LoginUser(final String email, final String password) {
String tag_string_req = "request_register";
pDialog.setMessage("Giriş Yapılıyor ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
JSONObject user = jObj.getJSONObject("user");
int userId = user.getInt("UserId");
int uId = user.getInt("UId");
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("UserId", userId);
intent.putExtra("UId", uId);
startActivity(intent);
finish();
} else {
String errorMsg = jObj.getString("message");
Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show();
hideDialog();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("password", password);
return params;
}
};
strReq.setShouldCache(false);
LoginApplication.getInstance().addToRequestQueue(strReq, tag_string_req);
}
This code is get datas about user at after login function:
public void Sync(final Context context, final int uId)
{
String tag_string_req = "request_syncUser";
db1 = new Database(context);
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//gelen tüm verileri local db ye at
try {
SQLiteDatabase db = db1.getWritableDatabase();
JSONObject jObj = new JSONObject(response);
JSONArray responseUser = jObj.getJSONArray("user");
boolean error = jObj.getBoolean("error");
String message = jObj.getString("message");
if(!error) {
for(int i=0; i<responseUser.length(); i++)
{
JSONObject user = responseUser.getJSONObject(i);
String u_name = user.getString("Name");
String u_surname = user.getString("Surname");
String u_email = user.getString("Email");
String u_password = user.getString("Password");
String u_isLogin = user.getString("isLogin");
String u_isSync = user.getString("isSync");
int u_uId = user.getInt("UId");
ContentValues cv = new ContentValues();
cv.put("Name", u_name);
cv.put("Surname", u_surname);
cv.put("Email", u_email);
cv.put("Password", u_password);
cv.put("isLogin", u_isLogin);
cv.put("isSync", u_isSync);
cv.put("UId", u_uId);
db.insertOrThrow("user", null, cv);
Toast.makeText(context, message ,Toast.LENGTH_LONG).show();
Toast.makeText(context, u_name + u_surname,Toast.LENGTH_LONG).show();
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("uId", String.valueOf(uId));
return params;
}
};
strReq.setShouldCache(false);
LoginApplication.getInstance().addToRequestQueue(strReq, tag_string_req);
}
}
Well we need to see your code?
That said my guess is you are not creating / accessing your queue in a singleton pattern. Complete guess. Always always always post code.
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.
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