Android Volley unable to get data in response - java

I am trying to make a web-service call using volley and printing the response in the logcat. But I don't know why I am not getting response. Not even any error message.
Below is my code. I know I am missing something. Please correct me.
private void syncData() {
mProgressDialog.showProgressDialog("Initializing Please Wait...");
RequestQueue requestQueue = Volley.newRequestQueue(SalesDashboard.this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, SYNC_DATA_SALES, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
mProgressDialog.dismissProgressDialog();
Log.e("TAG", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mProgressDialog.dismissProgressDialog();
Log.e("TAG", error.toString());
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String , String> params = new HashMap<>();
String userrole = mSessionManagement.getLoggedInUser().get(SESSION_USER_ROLE);
params.put("branch", mSessionManagement.getSelectedBranch());
params.put("staff_id", mSessionManagement.getLoggedInUser().get(SESSION_EMP_ID));
params.put("user_role", mSessionManagement.getLoggedInUser().get(SESSION_USER_ROLE));
params.put("user_dept", mSessionManagement.getLoggedInUser().get(SESSION_DEPT_IDS));
params.put("principal", mSessionManagement.getLoggedInUser().get(SESSION_PRINC_IDS));
if (userrole.equals(ADMIN) || userrole.equals(COUNTRY_MANAGER)) {
params.put("user_div", mSessionManagement.getSelectedDivision());
} else {
params.put("user_div", mSessionManagement.getLoggedInUser().get(SESSION_DIV_IDS));
}
return super.getParams();
}
};
requestQueue.add(stringRequest);
}
I am not receiving any error message also or any kind of exception. I have checked the webservice by hitting it on browser the response is displayed correctly on the browser but not able to fetch it in android.

Why you call super.getParams() on return instead params? Maybe it turn wrong on your request. Then try as follow
#Override
protected Map<String, String> getParams() throws AuthFailureError {
...
return params;
}
Bonus: use getMessage instead do toString() your error object

Print the stringRequest and check the url and cross verify with ur url
Before that check have u added Internet permissions in manifest file.

Related

Android JSON request with Volley

I am trying to register some data with an api and I have checked the json that I get in my application and the structure and data are fine, I put it in Postman and it works fine, the url is also fine, someone could help me to know what I am doing wrong ?
this is the method with which I try to make the call to the api
private void request2(final String json){
// Instantiate the RequestQueue.
RequestQueue mRequestQueue = SingletonRequestQueue.getInstance(getApplicationContext()).getRequestQueue();
// Request a string response from the provided URL.
StringRequest stringRequestPOSTJSON = new StringRequest(Request.Method.POST, BASE_URL + "/api/Asociado/RegistrarAsociado", new Response.Listener() {
#Override
public void onResponse(Object response) {
// response..
}
}, errorListener) {
#Override
public Priority getPriority() {
return Priority.HIGH;
}
#Override
public Map getHeaders() throws AuthFailureError {
HashMap headers = new HashMap();
headers.put("Authorization", "Bearer "+ bearertoken);
return headers;
}
#Override
public byte[] getBody() throws AuthFailureError {
String your_string_json = json; // put your json
return your_string_json.getBytes();
}
};
// Add the request to the RequestQueue.
mRequestQueue.add(stringRequestPOSTJSON);
}
This is the error I get: E/Volley: [4146] BasicNetwork.performRequest: Unexpected response code 400 for
try this code:
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
30000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

Volley is not requesting new Request after manually change the time while app is open

I have an Android app which calls web services using Volley. If my app is being opened and I manually change the time (backward or forward), Volley is not triggering new requests and the response which is already in the cache is returning. If I clear cache and data, only then the new request will trigger and new response will appear. How the Volley requests are related to system time and why this is happening? Is there any solution for this?
StringRequest stringRequest = new StringRequest(Request.Method.POST, new ServiceUtils().url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Log.d(TAG, "onResponse: response " + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Log.d(TAG, "onErrorResponse: " + error);
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> nameValuePairs = new HashMap<String, String>();
nameValuePairs.put("parm1", parm1);
nameValuePairs.put("parm2", parm2);
nameValuePairs.put("parm3", parm3);
return nameValuePairs;
}
};
addToRequestQueue(stringRequest, "", getApplicationContext());
Volley caches any request automatically and to overcome this situation, you need to set the setShouldCache attribute to false.
request.setShouldCache(false);
myQueue.getCache().clear();
myQueue.add(request);
Here's a full request copied from the Github issue.
RequestQueue queue = Volley.newRequestQueue(context);
queue.getCache().clear();
StringRequest myReq = new StringRequest(Request.Method.POST,
VolleyConnector.url,
createMyReqSuccessListener(),
createMyReqErrorListener()) {
protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Cn","1");
params.put("Yr","1396");
params.put("MaxInPage","10");
params.put("Method","Control_Vaziat_View");
params.put("Pg","1");
return params;
};
};
myReq.setShouldCache(false);
queue.add(myReq);
Hope that helps!

Android can not send post request with volley(BasicNetwork.performRequest: Unexpected response code 404)

I am trying to send some info to my api with post method(volley), but keep getting errors. Most consistent and the latest one is
E/Volley: [1449] BasicNetwork.performRequest: Unexpected response code 404 for http://....
D/Error.Response: com.android.volley.ClientError
I am able to post it with postman but not in android. I am sure nothing is wrong in the other side. I don't know what to do.
I have tried several implementations with getheader(),getBodyContentType(), Json object, string, parsing, try catch and so on..
RequestQueue queue = Volley.newRequestQueue(this);
String url = "....";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show();
Log.d("Error.Response", error.toString());
}
}
) {
#Override
public Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("email", "test#email.com");
params.put("token", "token");
return params;
}
};
queue.add(postRequest);

Android: Error connecting Android app with Database using php and json

My android app needs to send a string, and based on that, needs to get a response from the database.
I have a php that receives the string from the app, queries the database, and returns the response using echo json_encode($response_array); which works fine on the browser and echoes in a json object format.
However, In the app, I am using Volley. The php array $response_array above sends multiple strings which i need to display in the app textview.
I have set up volley in the gradle dependencies.
However, on running the app from my phone (which is connected on my laptop hotspot), the error i get is "null". This is the sample code from the app.
TextView o,t;
private RequestQueue requestQueue;
private static final String URL = "http://172.25.33.189/fadapp/mirror.php";
private StringRequest request;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
o=(TextView)findViewById(R.id.tryOne);
t=(TextView)findViewById(R.id.tryTwo);
requestQueue = Volley.newRequestQueue(this);
request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonobject = new JSONObject(response);
if (jsonobject.names().get(0).equals("name")) {
o.setText(jsonobject.getString("name"));
if(jsonobject.getString("stat").equals("1")) {
t.setText(R.string.inText);
t.setTextColor(Color.parseColor("#00FF00"));
} else {
t.setText(R.string.outText);
t.setTextColor(Color.parseColor("#FF0000"));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, ""+error.getMessage(), Toast.LENGTH_SHORT).show();;
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("speid", "database query string here");
return hashMap;
}
};
requestQueue.add(request);
Have you grant the intenet access to the app with ?
If you are hosting from your laptop you may need to open the port 80, to be sure that the problem isn't yor Volley set-up try to query for example google and print the response that should be a 200 http code

Pass parameters to volley with the PUT method

I'm using this simple code :
JsonObjectRequest req = new JsonObjectRequest(Request.Method.PUT, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
delegate.postNotificationSucced();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Log.d(TAG, ""+error.getMessage()+","+error.toString());
delegate.postNotificationFailed((APIErrors) error);
}
}){
#Override
public Map<String, String> getParams() throws AuthFailureError {
Map<String,String> headers = new HashMap<String, String>();
headers.put("Content-Type","application/x-www-form-urlencoded");
headers.put("state", Boolean.toString(isChecked));
return headers;
}
#Override
protected VolleyError parseNetworkError(VolleyError volleyError){
APIErrors error = null;
if(volleyError.networkResponse != null && volleyError.networkResponse.data != null){
error = new APIErrors(new String(volleyError.networkResponse.data));
}
return error;
}
};
When I use the Request.Method.GET or POST instead of PUT, the getParams() method is called but not with the PUT method.
My problem is that my API requires a PUT method.
How can I pass my parameters using the PUT method.
Edit :
With the PUT method the getHeaders() method is called, so can I pass my arguments through it ?
Solution :
In my case I solved the problem changing my JsonObjecRequest to StringRequest like suggested by #ishmaelMakitla. And now I pass inside getParams().
I noticed that you are not using the response object for anything - so
perhaps change the request from JsonObjectRequest to a StringRequest -
remember that you then need to change Response.Listener()
to Response.Listener() and the onResponse(JSONObject response)
to onResponse(String response)....shout if you need further help. I
hope this leads to some workable solution.
The reason is that with JsonObjectRequest, parameters must be pass through the third parameters of the constructor
jsonRequest - A JSONObject to post with the request. Null is allowed
and indicates no parameters will be posted along with request.
you can read the doc for more informations.
Since you are not using the response object for anything - you should change the request from JsonObjectRequest to a StringRequest - remember that you then need to change Response.Listener<JSONObject>() to Response.Listener<String>() and the onResponse(JSONObject response) to onResponse(String response).... here is StringRequest Gist I created - you can simply "plug-and-play" in your code and replace the JsonObjectRequest code.

Categories

Resources