Volley request takes to much time - java

I had implemented the volley request before and it was working perfectly, with some changes i did it stoped working like i want ( i will explain the changes after code).
So basicly i want to request to volley passing 4 parameters (the method, the url, the token and the data)
so i do something like this:
IResult mResultCallback2 = null;
public void sendFotoServer(){
String url = connectionTxt + "/fotos/" + specieId + "/plants";
HashMap<String,String> params = new HashMap<String, String>();
byte[] capture = encodeImage(b);
String encodedImage = Base64.encodeToString(capture,1);
Log.d("encodedImage",encodedImage);
params.put("base64", encodedImage);
params.put("lat",String.valueOf(photo.getLat()));
params.put("lon",String.valueOf(photo.getLon()));
params.put("alt",String.valueOf(photo.getAlt()));
params.put("date",photo.getTime());
JSONObject sendObj = new JSONObject(params);
PostPhotoVolleyCallback();
mVolleyService = new VolleyService(mResultCallback2, this);
mVolleyService.postDataVolley("POSTCALL", url, sendObj,token);
}
void PostPhotoVolleyCallback(){
mResultCallback2 = new IResult() {
#Override
public void notifySuccess(String requestType, JSONObject response) {
Log.d("HELLO","HELLOTHERE");
Log.d("resposta2",response.toString());
Intent intent = new Intent(SimiliarPhotos.this,PlantFeed.class);
startActivity(intent);
}
#Override
public void notifySuccess(String requestType, JSONArray response) {
Log.d("HELLO",response.toString());
}
#Override
public void notifyError(String requestType, VolleyError error) {
Log.d("errorV",error.getStackTrace().toString());
}
};
}
i have defined a interface so i can reuse the calls to volley like this:
package com.example.afcosta.inesctec.pt.android.services;
import android.content.Context;
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.afcosta.inesctec.pt.android.interfaces.IResult;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
/**
* Created by FilipeCosta on 19/05/2017.
*/
public class VolleyService {
IResult mResultCallback = null;
Context mContext;
public VolleyService(IResult resultCallback, Context context){
mResultCallback = resultCallback;
mContext = context;
}
public void postDataVolleyAuth(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);
}
}
});
jsonObj.setRetryPolicy(new DefaultRetryPolicy(30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(jsonObj);
}catch(Exception e){
}
}
public void postDataVolley(final String requestType,String url,JSONObject sendObj,final String token){
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);
}
}
}) {
#Override
public Map<String, String> getHeaders() {
Map<String, String> headers = new HashMap<>();
Log.d("tokenXX", token);
headers.put("x-access-token", token);
return headers;
}
};
jsonObj.setRetryPolicy(new DefaultRetryPolicy(30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(jsonObj);
}catch(Exception e){
}
}
public void getDataVolley(final String requestType, String url, final String token){
try {
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonArrayRequest jsonArray = new JsonArrayRequest(Request.Method.GET, url,null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if(mResultCallback != null)
mResultCallback.notifySuccess(requestType, response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public Map<String, String> getHeaders(){
Map<String, String> headers = new HashMap<>();
Log.d("tokenXX",token);
headers.put("x-access-token", token);
return headers;
}
};
jsonArray.setRetryPolicy(new DefaultRetryPolicy(30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(jsonArray);
}catch(Exception e){
}
}
public void getDataObjectVolley(final String requestType, String url, final String token){
try {
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,null, 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) {
}
}) {
#Override
public Map<String, String> getHeaders(){
Map<String, String> headers = new HashMap<>();
Log.d("tokenXX",token);
headers.put("x-access-token", token);
return headers;
}
};
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(jsonObjectRequest);
}catch(Exception e){
}
}
public void putDataVolley(final String requestType, String url, final String token){
try {
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObj = new JsonObjectRequest(Request.Method.PUT,url,null, 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);
}
}
}){
#Override
public Map<String, String> getHeaders(){
Map<String, String> headers = new HashMap<>();
Log.d("tokenXX",token);
headers.put("x-access-token", token);
return headers;
}
};
jsonObj.setRetryPolicy(new DefaultRetryPolicy(30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(jsonObj);
}catch(Exception e){
}
}
}
the problem is that i get a response but just like 5 minutes later, something like this:
POST /fotos/10/plants - - ms - -
POST /fotos/10/plants - - ms - -
POST /fotos/10/plants - - ms - -
POST /fotos/10/plants - - ms - -
POST /fotos/10/plants - - ms - -
POST /fotos/10/plants - - ms - -
POST /fotos/10/plants - - ms - -
POST /fotos/10/plants - - ms - -
POST /fotos/10/plants - - ms - -
the only thing that i changed was the way i get the data on this activity, at begin my model was a serializable, i changed it to parcelable, i pass my image trough a file and convert it to byte[] and after base64, i tried to debug and all my data was present, any tip here?
Thanks :)

Related

HTTP POST Request as a different Java Class - Android Studio

I am a complete noob to Android Studio, Java and Stack Overflow. My app performs a lot of HTTP Post requests using Volley and hence I've made an independent Java class with the code to perform the post request.
public class HTTPReq {
String[] finalResponse = new String[1];
public String postRequest(final HashMap<String,String> params, final Context context) {
RequestQueue requestQueue = Volley.newRequestQueue(context);
String url = "https://reqres.in/api/login";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
finalResponse[0] = response;
Toast.makeText(context, "2" + finalResponse[0], Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
finalResponse[1] = error.getMessage();
//Toast.makeText(context, "Response Failed", Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
return params;
}
#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;
}
};
requestQueue.add(stringRequest);
Toast.makeText(context, "3" + finalResponse[0], Toast.LENGTH_LONG).show();
return finalResponse[0];
}
}
What I'm trying to achieve is to get the response of the http request to the function call using return.
The function call is as follows:
public void login(String phno, String password,Context context)
{
HashMap<String,String> credentials = new HashMap<String, String>();
credentials.put("email","eve.holt#reqres.in");
credentials.put("password","cityslicka");
HTTPReq httpReq = new HTTPReq();
String response = httpReq.postRequest(credentials,context);
Toast.makeText(context, "1" + response, Toast.LENGTH_LONG).show();
}
I hope it's clear what I'm trying to achieve. Please help me with this.
your con use feature interface
public class HTTPReq {
public void postRequest(final HashMap<String, String> params, final Context context, final ResponseCallBack callBack) {
RequestQueue requestQueue = Volley.newRequestQueue(context);
String url = "https://reqres.in/api/login";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
callBack.onResponse(response);
Toast.makeText(context, response, Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
callBack.onError(error);
Toast.makeText(context, "Response Failed", Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
return params;
}
#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;
}
};
requestQueue.add(stringRequest);
}
}
calss interface :
import com.android.volley.VolleyError;
public interface ResponseCallBack<T> {
public void onResponse(T response);
public void onError(VolleyError error_response);
}
MainActivity:
public class MainActivity extends AppCompatActivity implements ResponseCallBack {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HTTPReq httpReq = new HTTPReq();
HashMap<String, String> credentials = new HashMap<String, String>();
credentials.put("email", "eve.holt#reqres.in");
credentials.put("password", "cityslicka");
httpReq.postRequest(credentials, this, this);
}
#Override
public void onResponse(Object response) {
Log.e("TAG", "onResponse: " + response);
}
#Override
public void onError(VolleyError error_response) {
Log.e("TAG", "onError: " + error_response);
}

HTTPPOST Android with Body

I was looking for an easy way to make an HTTP post in Android with body, my api call should be like :
https:url/api/message?token=myToken&channel=Pew&text=someText&username=User
What I did is this, I created this class
Public class ApiCalls {
private static PostCommentResponseListener mPostCommentResponse;
private static Context mContext;
public ApiCalls(){
}
public static void postNewComment(Context context, final String message){
mContext = context;
String apiUrl = context.getResources().getString(R.string.api_url);
mPostCommentResponse.requestStarted();
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest sr = new StringRequest(Request.Method.POST,apiUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
mPostCommentResponse.requestCompleted();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mPostCommentResponse.requestEndedWithError(error);
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("token",mContext.getResources().getString(R.string.access_token));
params.put("channel","pew");
params.put("text", message);
params.put("username","User");
return params;
}
#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;
}
};
queue.add(sr);
}
public interface PostCommentResponseListener {
public void requestStarted();
public void requestCompleted();
public void requestEndedWithError(VolleyError error);
}
}
But it doesn't work, it only shows app has stopped.
Is good to use Volley? Or you recommend to me to use other way? I used to use HttpClient but it's deprecated now...
What I'm missing?
Log error
java.lang.NullPointerException: Attempt to invoke interface method 'void com.package.ApiCalls$PostCommentResponseListener.requestStarted()' on a null object reference
You can send json body using volly as below two ways.
1. Using JsonObjectRequest
Map<String,String> params = new HashMap<String, String>();
params.put("token",mContext.getResources().getString(R.string.access_token));
params.put("channel","pew");
params.put("text", message);
params.put("username","User");
JsonObjectRequest request_json = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
//Process success response
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// handle error
}
});
// add the request object to the queue to be executed
queue.add(request_json);
2. Using JSON directly in request body
JSONObject jsonBody = new JSONObject();
jsonBody.put("token",mContext.getResources().getString(R.string.access_token));
jsonBody.put("channel","pew");
jsonBody.put("text", message);
jsonBody.put("username","User");
final String mRequestBody = jsonBody.toString();
StringRequest sr = new StringRequest(Request.Method.POST,apiUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Process success response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// handle error
}
}){
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody.getBytes("utf-8");
} catch (Exception e) {
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
// add the request object to the queue to be executed
queue.add((sr);
Initialise your mPostCommentResponse like this:
public ApiCalls(){
mPostCommmentResponse = (PostCommentResponseListener)mContext;
}
it will do you work and rest is fine. Thanks.
EDITED:
In Another Activity from where you want to call "ApiCall" class, do code like that:
new ApiCalls().postNewComment(AnotherActivity.this,"Your Messsage here");
and in method "postNewComment" do like this:
mContext = context;
mPostCommmentResponse = (PostCommentResponseListener)mContext;
Is it ok and understable??

Android Volley post json data to server

I am new in Java. I want to send post json data to webserver.
My Volley post is given below.
public void postData(String url,JSONObject data,final VolleyCallback mResultCallback){
RequestQueue requstQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonobj = new JsonObjectRequest(Request.Method.POST, url,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if(mResultCallback != null){
mResultCallback.notifySuccess(response);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null){
mResultCallback.notifyError(error);
}
}
}
){
//here I want to post data to sever
};
requstQueue.add(jsonobj);
}
Here is my MainActivity code
JSONObject data = null;
try {
String datas = "{'email': email,'password': password}";
data = new JSONObject(datas);
}catch (JSONException e){
e.printStackTrace();
}
String url = "http://example.com";
I want to post JSON data to my PostData method.
How can I post this json data to my server?
public void postData(String url,Hashmap data,final VolleyCallback mResultCallback){
RequestQueue requstQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonobj = new JsonObjectRequest(Request.Method.POST, url,new JSONObject(data),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if(mResultCallback != null){
mResultCallback.notifySuccess(response);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null){
mResultCallback.notifyError(error);
}
}
}
){
//here I want to post data to sever
};
requstQueue.add(jsonobj);
}
Now, from your mainActiviy class
Hashmap data = new HashMap();
data.put("email","email");
data.put("password","password");
String url = "http://example.com";
//now you can just call the method, I have rectified your string to hashmap,
postData(url,data,new mResultCallb..... //rest of your code
public void postData(String url,JSONObject data,final VolleyCallback mResultCallback){
RequestQueue requestQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonobj = new JsonObjectRequest(Request.Method.POST, url,data,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if(mResultCallback != null){
mResultCallback.notifySuccess(response);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null){
mResultCallback.notifyError(error);
}
}
}
);
requstQueue.add(jsonobj);
}
public void postData(String url,final JSONObject data,final VolleyCallback mResultCallback){
RequestQueue requstQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonobj = new JsonObjectRequest(Request.Method.POST, url,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if(mResultCallback != null){
mResultCallback.notifySuccess(response);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null){
mResultCallback.notifyError(error);
}
}
}
){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
if(data != null){
Iterator<String> keysItr = data.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = data.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
params.put(key, value);
}
}
return params;
}
};
requstQueue.add(jsonobj);
this is working code for me
Hope this might be work for you..
Happy Codding

How to send request Header is "Content-Type":"application/json" when GET on Volley

I try to use GET on Volley , but i need send request to application/json .
I take a look for some answers , i try to use jsonBody , but it shows error:
null com.android.volley.ServerError
Here is my code:
public class MainActivity extends AppCompatActivity {
String url = "http://114.35.246.42:2212/MobileApp/DEST_WebService.asmx/GetNews";
JSONObject jsonBody;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
//I try to use this for send Header is application/json
jsonBody = new JSONObject("{\"type\":\"example\"}");
} catch (JSONException ex) {
ex.printStackTrace();
}
RequestQueue mQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, jsonBody,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage(), error);
}
});
mQueue.add(jsonObjectRequest);
}
}
Is any one can teach me how to fix this , any help would be appreciated.
Here is my url:
String url = "http://114.35.246.42:2212/MobileApp/DEST_WebService.asmx/GetNews";
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
return params;
}
Implementation in your's
public class MainActivity extends AppCompatActivity {
String url = "http://114.35.246.42:2212/MobileApp/DEST_WebService.asmx/GetNews";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RequestQueue mQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, jsonBody,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage(), error);
}
}) { //no semicolon or coma
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
return params;
}
};
mQueue.add(jsonObjectRequest);
}
}
In general for setting a custom header you need to override getHeaders and set the custom header manually. However, volley handles content type headers differently and getHeaders way does not always work.
So for your case you need to override getBodyContentType. So your code will look like
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, jsonBody,new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage(), error);
}
}){
#Override
public String getBodyContentType(){
return "application/json";
}
};
I try to use GET on Volley
The docs for the method you are calling says this
Constructor which defaults to GET if jsonRequest is null, POST otherwise
You can't GET with an HTTP JSON body. Maybe that's the error.
//I try to use this for send Header is application/json
jsonBody = new JSONObject("{\"type\":\"example\"}");
That's not the header, so pass in null here to do GET
new JsonObjectRequest(url, null,
And towards the end of your request, override a method to request JSON
...
#Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage(), error);
}
}) { // Notice no semi-colon here
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
return params;
}
};
Use String request instead of jsonrequest like this
StringRequest loginMe = new StringRequest(Request.Method.GET, "http://114.35.246.42:2212/MobileApp/DEST_WebService.asmx/GetNews", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("LoginActivity -- onResponse --> " + response);
if (progressDialog != null) {
progressDialog.dismiss();
}
try {
JSONObject jsonObject = new JSONObject(response);
} catch (Exception e) {
CommonUtility.somethingWentWrongDialog(activity,
"LoginActivity -- onResponse-- Exception --> ".concat(e.getMessage()));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (progressDialog != null) {
progressDialog.dismiss();
}
CommonUtility.somethingWentWrongDialog(activity,
"LoginActivity -- onErrorResponse --> ".concat(error.getMessage()));
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
System.out.println("LoginActivity -- LoginParams --> " + params.toString());
return params;
}
};
loginMe.setRetryPolicy(new DefaultRetryPolicy(60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(activity).add(loginMe);

How to post boolean value using volley

I am trying to post boolean value using volley library.When a button is clicked,a boolean value is set to true.The boolean value is then posted to my php script to increment counter in my mysql database. i am getting an error in trying to add a request to queue. What am i doing wrong? This is my code
holder.custom_button.setOnClickListener(new View.OnClickListener() {
int count;
#Override
public void onClick(View v) {
count = 0;
superHeroes.get(position).setCount(superHeroes.get(position).getCount() + 1);
holder.txtCount.setText(superHeroes.get(position).getCount() + "");
final String url = "http://10.0.2.2/likes.php";
isLiked = true;
JSONObject obj = new JSONObject();
try {
obj.put("isLiked", true);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
// Access the RequestQueue through your singleton class.
// i am getting error here
customVolleyRequest.getInstance(this).addToRequestQueue(jsObjRequest);
}
});
SINGLETON
package net.simplifiedcoding.myfeed;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import com.android.volley.Cache;
import com.android.volley.Network;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.HurlStack;
import com.android.volley.toolbox.ImageLoader;
/**
* Created by Belal on 12/5/2015.
*/
public class CustomVolleyRequest {
private static CustomVolleyRequest customVolleyRequest;
private static Context context;
private RequestQueue requestQueue;
private ImageLoader imageLoader;
private CustomVolleyRequest(Context context) {
this.context = context;
this.requestQueue = getRequestQueue();
imageLoader = new ImageLoader(requestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static synchronized CustomVolleyRequest getInstance(Context context) {
if (customVolleyRequest == null) {
customVolleyRequest = new CustomVolleyRequest(context);
}
return customVolleyRequest;
}
public RequestQueue getRequestQueue() {
if (requestQueue == null) {
Cache cache = new DiskBasedCache(context.getCacheDir(), 10 * 1024 * 1024);
Network network = new BasicNetwork(new HurlStack());
requestQueue = new RequestQueue(cache, network);
requestQueue.start();
}
return requestQueue;
}
public ImageLoader getImageLoader() {
return imageLoader;
}
}
ERROR
'getInstance(android.content.Context)' in 'net.simplifiedcoding.myfeed.CustomVolleyRequest' cannot be applied to '(anonymous android.view.View.OnClickListener)'
You are not making POST request. You should do like this:
JsonObjectRequest req = new JsonObjectRequest( Request.Method.POST, url,
new JSONObject(jsonParams),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Handle response
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle Error
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
AppController.getInstance().addToRequestQueue(req); // AppController is Volley Singleton.
You have used CardAdapter, I don't what that is. You should always add the request object to Volley Singleton. Reference.

Categories