I work with android volley library! I have some don't understand problem with sending request with json and DELETE method from server. Request successfully connect to server but sended parameters server will receive is empty. But header request work normaly! Please help me!
public void deletePoint(String id) throws JSONException {
dialog.show();
queue = Volley.newRequestQueue(getActivity(), new ExtHttpClientStack(new SslHttpClient().getHttpClient()));
String urlRequest = getUrl();
JSONObject param = new JSONObject();
param.put("id", id);
JsonObjectRequest userRequest = new JsonObjectRequest(Request.Method.DELETE,
urlRequest,
param,
deletePointRequestSuccessListener(),
reqErrorListener()){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null || headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
if (ProgressFragment.this.headers != null) {
headers.keySet().removeAll(ProgressFragment.this.headers.keySet());
headers.putAll(ProgressFragment.this.headers);
}
headers.put("Content-Type", "application/json");
return headers;
}
};
userRequest.setRetryPolicy(new DefaultRetryPolicy(
MY_SOCKET_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
dialog.show();
queue.add(userRequest);
}
private Response.Listener<JSONObject> deletePointRequestSuccessListener() {
return new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
dialog.hide();
Gson gson = new Gson();
Success resp = gson.fromJson(response.toString(), Success.class);
if(resp.isSuccess()){
Toast.makeText(getActivity(), getString(R.string.success), Toast.LENGTH_SHORT).show();
try {
getGraphData();
} catch (JSONException e) {
e.printStackTrace();
}
}
dialog.hide();
}
};
}
it's this issue that has been resolved
you can rewrite the HurlStack class
public class HurlStack implements HttpStack {
break;
case Method.DELETE:
connection.setRequestMethod("DELETE");
addBodyIfExists(connection, request); // here call addBodyIfExists method
break;
case Method.POST:
connection.setRequestMethod("POST");
request with DELETE method will be easy as POST,for example
mQueue = Volley.newRequestQueue(context);
StringRequest postRequest = new StringRequest(Request.Method.DELETE, HttpUtils.URL_MSG,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
if (mCallBack!=null) {
mCallBack.success(response);
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
if (mCallBack!=null) {
mCallBack.fail(null);
}
}
}
) {
#Override
protected Map<String, String> getParams()
{
return params;
}
};
mQueue.add(postRequest);
that can only resolve android os 5.0 devices problem
there has new problem on android os 4.2.2 device
it will throw the following exception
java.net.ProtocolException: DELETE does not support writing
to rewrite Volley.newRequestQueue(Context context, HttpStack stack) method can resovle this problem
public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
.
.
.
if (stack == null) {
if (Build.VERSION.SDK_INT >= 9) {
stack = new OkHttpStack();
} else {
// Prior to Gingerbread, HttpUrlConnection was unreliable.
// See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
}
}
.
.
.
return queue;
}
OkHttpStack.java(okhttp-1.6.0.jar)
public class OkHttpStack extends HurlStack {
private final OkHttpClient client;
public OkHttpStack() {
this(new OkHttpClient());
}
public OkHttpStack(OkHttpClient client) {
if (client == null) {
throw new NullPointerException("Client must not be null.");
}
this.client = client;
}
#Override protected HttpURLConnection createConnection(URL url) throws IOException {
return client.open(url);
}
}
it works for me, hoping that work for you as well
Try to pass parameters with the URL as you would do with a GET request. Worked for me :)
Code sample (not tested):
url += "?";
for(String key : params.keyset()){
url += URLEncode.encode(key,"UTF-8") +"="+ URLEncode.encode( params.get(key),"UTF-8") +"&";
}
url = url.substring(0, url.length()-1); // remove last '&' char
Related
In My Activity it Checks the user credentials and returns session id and related info if valid. The Method is POST.The parameter has to send as JSON.
{
"params": {
"context": {},
"db": "testing",
"login": "admin",
"password": "admin"
}
}
So i create a JSONObject and send it as it is With Header.I am getting response in POSTMAN.But what i m getting error when i call it as it is.Can Any one help me in this?
private void volleyLogin() throws JSONException {
mProgressView.setVisibility(View.VISIBLE);
JSONObject one = new JSONObject();
one.put("context",new JSONObject());
one.put("db","testing");
one.put("login","admin");
one.put("password","admin");
JSONObject params = new JSONObject();
params.put("params",one);
HashMap<String, String> header = new HashMap<String, String>();
header.put("Content-Type", "application/json; charset=utf-8");
RequestQueue requestQueue = Volley.newRequestQueue(this);
CustomRequest jsObjRequest = new CustomRequest(Request.Method.POST,
ApiConstants.URL_AUTHENTICATE,params,header, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println("Response"+response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("VolleyError"+error);
}
}
);
jsObjRequest.setRetryPolicy(new DefaultRetryPolicy(
(int) TimeUnit.SECONDS.toMillis(120),
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
System.out.println("jsObjRequest"+jsObjRequest);
requestQueue.add(jsObjRequest);
}
Here is the Custom Request Class
public class CustomRequest extends Request<JSONObject> {
private Response.Listener<JSONObject> listener;
private JSONObject jsonObjectParams;
private Map<String, String> headers;
public CustomRequest(int method,String url, JSONObject jsonObjectParams,Map<String, String> headers,
Response.Listener<JSONObject> reponseListener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = reponseListener;
this.jsonObjectParams = jsonObjectParams;
this.headers= headers;
System.out.println("method"+method);
System.out.println("url"+url);
System.out.println("jsonObjectParams"+jsonObjectParams);
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers;
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
#Override
protected void deliverResponse(JSONObject response) {
// TODO Auto-generated method stub
listener.onResponse(response);
}
#Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
if(volleyError.networkResponse != null && volleyError.networkResponse.data != null){
VolleyError error = new VolleyError(new String(volleyError.networkResponse.data));
volleyError = error;
}
return volleyError;
}
}
You can try something like this:
Create a singletone class VolleyDispatcher, that holds the RequestQueue from volley.
public RequestQueue getRequestQueue() {
if (requestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
requestQueue = Volley.newRequestQueue(mContext.getApplicationContext());
}
return requestQueue;
}
/**
* Recreates the request queue using username/password https auth.
*/
public void recreateRequestQueue() {
if (!AppUtil.isEmpty(AppConstants.USERNAME) && !AppUtil.isEmpty(AppConstants.PASSWORD)) {//check if a user is logged in so that the https auth can be created if necessary
if (requestQueue != null) {
requestQueue.stop();
requestQueue = null;
}
requestQueue = Volley.newRequestQueue(mContext.getApplicationContext(), new HurlCustomStack());
}
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
Call recreateRequestQueue before doing any volley requests
Implement the custom HurlStack
public class HurlCustomStack extends HurlStack {
#Override
protected HttpURLConnection createConnection(URL url) throws IOException {
// Workaround for the M release HttpURLConnection not observing the
// HttpURLConnection.setFollowRedirects() property.
// https://code.google.com/p/android/issues/detail?id=194495
// connection.setInstanceFollowRedirects(HttpURLConnection.getFollowRedirects());
return HttpUrlConnectionHelper.getInstance().createHttpUrlConnection(url);
}
}
And the client creation method:
public HttpURLConnection createHttpUrlConnection(URL url) throws IOException {
Log.d(TAG, "Create http url connection with url : " + url.toString());
HttpURLConnection httpConnection = null;
if ("https".equalsIgnoreCase(url.getProtocol())) {
HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
https.setHostnameVerifier(DO_NOT_VERIFY);
httpConnection = https;
} else {
httpConnection = (HttpURLConnection) url.openConnection();
}
httpConnection.setReadTimeout(TIMEOUT);
httpConnection.setConnectTimeout(TIMEOUT);
String basicAuth = "Basic " + new String(Base64.encode((AppConstants.USERNAME + ":" + AppConstants.PASSWORD).getBytes(), Base64.NO_WRAP));
httpConnection.setRequestProperty("Authorization", basicAuth);
httpConnection.setRequestProperty("Accept-Language", Locale.getDefault().getLanguage());
return httpConnection;
}
So now, every time you want to make a request, just use the addToRequestQueue method in the VolleyDispatcher class.
hello everyone im facing a problem with volley delete request .
i working on task in user add or remove some contacts by it's id .
im using volley library for it.
API is tested with postman and working fine.
private void AddContactInList(final Contacts contacts,int RequestMethod) {
JSONArray ContactArray = new JSONArray();
ContactArray.put(StoredContactid);
final String jsonStr = ContactArray.toString();
String URl = OrganizationModel.getApiBaseUrl() + getOrgId() + "/lists/" + contacts.getId()+"/contacts";
Log.i(TAG,URl);
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
JsonObjectRequest jsonArrayRequest = new JsonObjectRequest(RequestMethod,URl,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG,response.toString());
try {
JSONArray mJSONArray = response.getJSONArray("contactIds");
contacts.setCode(String.valueOf(mJSONArray.length()));
long time = System.currentTimeMillis();
sqliteDataBaseHelper.changeContactUpdatedON(StoredContactid, String.valueOf(time));
sqliteDataBaseHelper.updateListContactsAndLength(contacts.getId(), mJSONArray.toString(), (mJSONArray.length()));
dataAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i(TAG,error.toString());
String json = null;
NetworkResponse response = error.networkResponse;
if (response != null && response.data != null) {
switch (response.statusCode) {
case 400:
case 405:
json = new String(response.data);
json = dataHelper.trimMessage(json, "message");
if (json != null) dataHelper.displayMessage(json);
break;
}
}
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() {
try {
return jsonStr == null ? null : jsonStr.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
jsonStr, "utf-8");
return null;
}
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
headers.put("Authorization", "Basic " + GetApiAccess());
return headers;
}
};
jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(
9000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonArrayRequest);
}
In my SQLite Database , the below code is working. Hope it may help you..
public void DeleteData(){
btnDltData.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer deleteRows = myDB.deleteData(editId.getText().toString());
if(deleteRows > 0)
Toast.makeText(MainActivity.this, "Task Clear..", Toast.LENGTH_SHORT).show();
else
Toast.makeText(MainActivity.this, "Task not Clear..", Toast.LENGTH_SHORT).show();
editId.setText("");
}
}
);
}
http://www.itsalif.info/content/android-volley-tutorial-http-get-post-put
try this, if problem didnt solve yet
I have not used volley library much. i have read the tutorials. i want to send data to a url which which will enter that data in database. i have tried the following code but its not working. data is not entered in the database.
String url = "http://tipseducation.com/system/eadmin/insertschedule/";
StringRequest sr = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Valid Response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//error message
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("appt_name", ed_name);
params.put("appt_email", ed_email);
params.put("appt_contact", ed_contact);
params.put("appt_date", ed_date);
params.put("appt_time", ed_time);
params.put("appt_service", ed_spinner);
return params;
}
};
can anyone please help me. iam new to this
Instead of getHeaders, you should use getBody for your POST request.
You can refer to my following working sample code (replace my JSONObject and Url by yours). Hope this helps!
...
try {
RequestQueue queue = Volley.newRequestQueue(this);
jsonBody = new JSONObject();
jsonBody.put("Title", "Android Volley POST DATA Demo");
jsonBody.put("Author", "BNK");
jsonBody.put("Date", "2015/09/17");
requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(1, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// do something...
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// do something...
}
}) {
#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) {
e.printStackTrace();
return null;
}
}
};
queue.addToRequestQueue(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
...
I am trying to use DWorkS/VolleyPlus to make a MultiPartRequest.
I have searched through the GitHub repository, and it's sample code, but I can find no examples using this class.
I am getting a 411 response code when I make my request. My understanding is that this is sent by the server as a response when it refuses to accept a message without a content-length header. How would I go about providing this?
Below is the relevant part of the LogCat showing the error, and my method.
Looking at the code for MultiPartRequest, it has a field called isFixedStreamingMode. This name sounds similar to setFixedLengthStreamingMode for a connection, however I can't see where it ever gets used in the code. Also it is a boolean not an int, so I cannot supply a length with it. Does anyone know what this field is for?
Has anyone successfully used MultiPartRequest from this library? Any advice or examples would be greatly appreciated.
I am currently successfully making POST, GET and PUT methods using the StringRequest class from this library.
LogCat
03-11 22:17:15.388 25236-25236/au.com.xxx.yyy D/MainActivity﹕ postMyItem: http://yyy.zzz.com.au/api/v1/my_item
03-11 22:17:15.507 25236-25309/au.com.xxx.yyy E/Volley﹕ [5861] BasicNetwork.performRequest: Unexpected response code 411 for http://yyy.zzz.com.au/api/v1/my_item
03-11 22:17:15.508 25236-25236/au.com.xxx.yyy D/MainActivity﹕ error response: <html>
<head><title>411 Length Required</title></head>
<body bgcolor="white">
<center><h1>411 Length Required</h1></center>
<hr><center>nginx/1.1.19</center>
</body>
</html>
03-11 22:17:15.508 25236-25236/au.com.xxx.yyy D/MainActivity﹕ Volley Error: com.android.volley.error.VolleyError
Method
public void postMyItem(final MyItem myItem) {
String url = getString(R.string.url__server_api) + getString(R.string.post__my_item);
MultiPartRequest request = new MultiPartRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Volley POST MyItem response: " + response);
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Volley Error: " + error);
try {
String response = new String(error.networkResponse.data, "utf-8");
Log.d(TAG, "error response: " + response);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
})
{
#Override
protected Response parseNetworkResponse(NetworkResponse networkResponse) {
return null;
}
#Override
public Map<String, String> getHeaders() throws com.android.volley.error.AuthFailureError {
Map<String, String> map = new HashMap<>();
map.put(getString(R.string.header_field__access_token), mAccess_token);
return map;
}
};
if (myItem.name != null) {
request.addMultipartParam("name", "multipart/mixed", myItem.name);
}
if (myItem.quantity != null) {
request.addMultipartParam("quantity", "multipart/mixed", myItem.quantity);
}
...
//TODO: request.addFile(name, filePath)
VolleySingleton.getInstance(this).addToRequestQueue(request);
}
So sometime the servers might require content length to be told before uploading imagesetFixedStreamingMode is the method. The sample code is below
SimpleMultipartRequest request = new SimpleMultipartRequest(Method.POST, apiUrl, mListener, mErrorListener);
request.addFile("photo", image_path);
RequestQueue mRequestQueue = Volley.newRequestQueue(getApplicationContext());
mRequestQueue.add(request);
mRequestQueue.setFixedStreamingMode(true);
mRequestQueue.start();
You can use MultipartEntitiy in volley request for adding multipart data in your request body, by overriding getBody method like this:
public class MultipartRequest extends Request<String> {
private MultipartEntity entity = new MultipartEntity();
private static final String FILE_PART_NAME = "file";
private static final String STRING_PART_NAME = "text";
private static final String SELFIE_IMAGE = "selfieImage";
private static final String SELFIE_CAPTION = "cap";
private final Response.Listener<String> mListener;
private final File mFilePart;
private final String mStringPart;
public MultipartRequest(String url, Response.ErrorListener errorListener, Response.Listener<String> listener, File file, String stringPart)
{
super(Method.POST, url, errorListener);
mListener = listener;
mFilePart = file;
mStringPart = stringPart;
buildMultipartEntity();
}
private void buildMultipartEntity()
{ System.out.println("buildMultipartEntity");
entity.addPart(SELFIE_IMAGE, new FileBody(mFilePart));
try
{
entity.addPart(SELFIE_CAPTION, new StringBody(mStringPart));
}
catch (UnsupportedEncodingException e)
{
VolleyLog.e("UnsupportedEncodingException");
}
}
#Override
public String getBodyContentType()
{ System.out.println("getBodyContentType");
return entity.getContentType().getValue();
}
#Override
public byte[] getBody() throws AuthFailureError{
System.out.println("getBody");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try
{
entity.writeTo(bos);
}
catch (IOException e)
{
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response)
{
return Response.success("Uploaded", getCacheEntry());
}
#Override
protected void deliverResponse(String response)
{
mListener.onResponse(response);
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
System.out.println("getHeaders");
if (headers == null
|| headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
AppController.getInstance().addSessionCookie(headers);
return headers;
}
}
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