I try to execute a new volley request in the current volley request, but when the new request is called it don't step into the onrespond method.
The new request should be executed before the first ends. (Last in, first out)
How can I execute the new request succesfully ?
private void makeJsonObjectRequest() {
ac = new AppController();
final JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("test", response.toString());
try {
// Parsing json object response
// response will be a json object
JSONArray name = response.getJSONArray("data");
for (int i = 0; i < name.length(); i++) {
JSONObject post = (JSONObject) name.getJSONObject(i);
try {
objectid = post.getString("object_id");
newRequest(objectid);
}
catch (Exception e) {
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("test", "Error: " + error.getMessage());
}
});
// Adding request to request queue
ac.getInstance().addToRequestQueue(jsonObjReq);
}
Try it Work 100%
public class Utility {
String result = "";
String tag_string_req = "string_raq";
private Activity activity;
Context context;
private LinearLayout mLinear;
private ProgressDialog pDialog;
public Utility(Context context) {
this.context = context;
}
public String getString(String url, final VolleyCallback callback) {
showpDialog();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
result = response;
hideDialog();
callback.onSuccess(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
callback.onRequestError(error);
hideDialog();
/*LayoutInflater inflater = ((Activity) context).getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast, null);
((Activity) context).setContentView(layout);*/
}
});
VolleySingleton.getInstance().addToRequestQueue(stringRequest, tag_string_req);
stringRequest.setRetryPolicy(
new DefaultRetryPolicy(1 * 1000, 1, 1.0f));
return result;
}
public interface VolleyCallback {
void onSuccess(String result);
void onRequestError(VolleyError errorMessage);
//void onJsonInvoke(String url, final VolleyCallback callback);
}
public boolean isOnline() {
Runtime runtime = Runtime.getRuntime();
try {
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = ipProcess.waitFor();
return (exitValue == 0);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return false;
}
private void showpDialog() {
onProgress();
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
public void onProgress() {
pDialog = new ProgressDialog(context);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
}
}
Call Fragment
Utility utility = new Utility(getContext());
utility.getString(urls, new Utility.VolleyCallback() {
#Override
public void onSuccess(String result) {
try {
JSONObject toplinks = new JSONObject(result);
JSONObject data = toplinks.getJSONObject("toplinks");
M.i("============LS", "" + data);
} catch (JSONException e) {
e.printStackTrace();
}
finally {
}
}
#Override
public void onRequestError(VolleyError errorMessage) {
errorJson.setVisibility(View.VISIBLE);
String msg = VolleyException.getErrorMessageFromVolleyError(errorMessage);
errorJson.setText(msg);
}
});
all this about
Request Prioritization
Networking calls is real time operation so let consider we have multi request like in your case , Volley processes the requests from higher priorities to lower priorities , in first-in-first-out order.
So all you need change priority (set Priority.HIGH) to request you want process first.
here is a piece of code
public class CustomPriorityRequest extends JsonObjectRequest {
// default value
Priority mPriority = Priority.HIGH;
public CustomPriorityRequest(int method, String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(method, url, jsonRequest, listener, errorListener);
}
public CustomPriorityRequest(String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(url, jsonRequest, listener, errorListener);
}
#Override
public Priority getPriority() {
return mPriority;
}
public void setPriority(Priority p){
mPriority = p;
}
}
As others mentioned one way is to put a high priority on the request.
Another option as it seems you have the first request depending on the inner one wrapped in the try-catch block which seems to me you want to achieve a synchronous/blocking behavior for this specific case. then you can use RequestFuture :
RequestFuture<String> future = RequestFuture.newFuture();
StringRequest request = newRequest(objectid, future);
requestQueue.add(request);
String result = future.get();
Related
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.
I am sending server request to handle response and error i have implemented interface. I just want to know how to handle if "mResultCallBack ==null" without editing condition if(mResultCallBack!=null). code are as follow:-
public Context mContext;
private IResult mResultCallBack;
public CServerRequest(IResult mResultCallBack, Context context) {
this.mContext = context;
this.mResultCallBack = mResultCallBack;
}
public void postWalletRequest(final String requestType, String url, JSONObject jsonObject) {
try {
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
mResultCallBack.notifySuccess(requestType, response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mResultCallBack.notifyError(requestType, error);
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(jsonObjectRequest);
} catch (Exception e) {
e.printStackTrace();
}
}
}
and code for interface
public void notifySuccess(String requestType,JSONObject response);
public void notifyError(String requestType,VolleyError error);
AsyncTask.execute(new Runnable() {
#Override
public void run() {
if (loginSessionManager.isLogin()){
cServerRequest = new CServerRequest(mResultcallBack,mContext);
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject();
jsonObject.put(CRequestKey.AGENT_CODE, m_szMobileNumber.trim());// sending mobile no.(static right know becuse of ser side data on other is null
jsonObject.put(CRequestKey.PIN, m_szEncryptedPassword.trim());// same here as said above
Log.e(TAG,"Request::"+jsonObject.toString());
} catch (JSONException e) {
e.printStackTrace();
}
final String s_szWalletURL = CAPIStorage.IREWARDS_URL + CAPIStorage.WALLET_BALANCE_URL;
cServerRequest.postWalletRequest("POST",s_szWalletURL,jsonObject);
}else {
Log.e(TAG,"Not loggedin");
}
}
});
public Context mContext;
private IResult mResultCallBack;
public CServerRequest(IResult mResultCallBack, Context context) {
this.mContext = context;
this.mResultCallBack = mResultCallBack;
}
public void postWalletRequest(final String requestType, String url, JSONObject jsonObject) {
try {
if(jsonObject.getJSONArray.length() == 0) {
System.out.println("JSONArray is null");
}
else{
System.out.println("JSONArray is not null");
//parse your string here
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
mResultCallBack.notifySuccess(requestType, response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mResultCallBack.notifyError(requestType, error);
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(jsonObjectRequest);
}
} catch (Exception e) {
e.printStackTrace();
}
}
I can't find any solution to this. As of now it seems I have to choose between getting the normal html response or getting only the response headers.
Is there a way to modify my code to get both of these?
Current code (Gives response headers only)
StringRequest stringRequest = new StringRequest(Request.Method.GET, loginURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String responseSession = response.substring(0,response.indexOf(";"));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this,error.toString(),Toast.LENGTH_LONG ).show();
}
}){
#Override
protected Response<String> parseNetworkResponse(NetworkResponse networkResponse) {
String sessionId = networkResponse.headers.get("Set-Cookie");
com.android.volley.Response<String> result = com.android.volley.Response.success(sessionId,
HttpHeaderParser.parseCacheHeaders(networkResponse));
return result;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
Use a custom request class for this purpose,
public class CustomStringRequest extends Request<CustomStringRequest.ResponseM> {
private Response.Listener<CustomStringRequest.ResponseM> mListener;
public CustomStringRequest(int method, String url, Response.Listener<CustomStringRequest.ResponseM> responseListener, Response.ErrorListener listener) {
super(method, url, listener);
this.mListener = responseListener;
}
#Override
protected void deliverResponse(ResponseM response) {
this.mListener.onResponse(response);
}
#Override
protected Response<ResponseM> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
ResponseM responseM = new ResponseM();
responseM.headers = response.headers;
responseM.response = parsed;
return Response.success(responseM, HttpHeaderParser.parseCacheHeaders(response));
}
public static class ResponseM {
Map<String, String> headers;
String response;
}
}
And change the code like this ,
CustomStringRequest stringRequest = new CustomStringRequest(Request.Method.GET, loginURL,
new Response.Listener<CustomStringRequest.ResponseM>() {
#Override
public void onResponse(CustomStringRequest.ResponseM result) {
//From here you will get headers
String sessionId = result.headers.get("Set-Cookie");
String responseString = result.response;
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this,error.toString(),Toast.LENGTH_LONG ).show();
}
}) {
};
When I call getData.It seems that it is hard to get the result out from the onResponse. I know it cannot work in this current way. Could anyone help me to settle this problem?
getData()
private void getData(){
//Creating a string request
StringRequest stringRequest = new StringRequest(SPINNER_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Log.d("Country_name","hi");
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray(JSON_ARRAY);
Log.v("xxxxx",result.toString());
String mysh=result.toString().substring(1, result.toString().length()-1);
JSONArray jsonArray = new JSONArray(mysh);
//Calling method getCountry to get the country from the JSON Array
getCountry(jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
Try this i think it should work
private void getData(){
//Creating a string request
StringRequest stringRequest = new StringRequest(SPINNER_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
getCountry(jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Try that, this will help.
private void getData() {
String tag_string_req = "req_name";
spotsDialog.show();
StringRequest strReq = new StringRequest(Method.POST,
YOUR URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Response: " + response.toString());
try {
JSONObject object = new JSONObject(response);
JSONArray array = object.getJSONArray("YOUR ARRAY NAME");
for (int i=0;i<array.length();i++){
String result = array.getString(i).toString();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
}
});
strReq.setRetryPolicy(new RetryPolicy() {
#Override
public void retry(VolleyError arg0) throws VolleyError {
}
#Override
public int getCurrentTimeout() {
return 0;
}
#Override
public int getCurrentRetryCount() {
return 0;
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
Happy To Help.
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