How to fix null response using JsonArrayRequest using a Get method? - android

I am getting a null response when I make a call to the Get method using a JsonArrayRequest.
I tried both OnResponse and parseNetworkResponse override methods in the request but still the response is null.
String url = "http://myUrl";
RequestQueue requestQueue = Volley.newRequestQueue(mContext);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null , new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.i("TAG",response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("on Error Response", error.toString());
}
})
{
#Override
public Map<String, String> getHeaders() {
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
return headers;
}
#Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
int statusCode = response.statusCode;
switch (statusCode) {
case 200:
Log.i("TAG1", response.toString());
}
return null;
}
};
requestQueue.add(jsonArrayRequest);
I am expecting to get a json array consist of three json objects
I also used this :
return Response.success(response, HttpHeaderParser.parseCacheHeaders(response));
still response is null.

Related

Unable to handle volley response as JsonObject

I have an API which returns the response like "[{"VideoReferenceURL":"x0DE_VDEEAw"}]"
I need to capture the value of "VideoReferenceURL" variable into a string variable "videoURL"
But when i use below code, the method is not getting into onResponse.
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
requestUrl, null, new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
try {
String videoURL = response.getString("VideoReferenceURL");
Log.d("VideoURL",videoURL);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
progressDialog.hide();
Log.d("myerror","I got some error");
NetworkResponse networkResponse = error.networkResponse;
Log.d("myerror1",error.getMessage());
// Toast.makeText(getApplicationContext(),error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError
{
Map<String, String> headers = new HashMap<>();
String credentials = Constants.WS_Username+":"+Constants.WS_Password;
String auth = "Basic "
+ Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
headers.put("Content-Type", "application/json");
headers.put("Authorization", auth);
return headers;
}
};
RequestHandler.getInstance(_context).addToRequestQueue(jsonObjReq);
When i use above with StringRequest, i am getting into onResponse, but response is having entire String rather than JSON. I need to write custom string logic to extra the required value.
StringRequest stringRequest=new StringRequest(
Request.Method.GET, requestUrl, new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
Log.d("VideoURL",response);
}
}
Tried below to handle as JSON, but it is still not getting into onResponse method
StringRequest stringRequest=new StringRequest(
Request.Method.GET, requestUrl, new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
try {
JSONObject object=new JSONObject(response);
Log.d("VideoURL",object.getString("VideoReferenceURL"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Can someone tell me what i am missing here?

how to write Google Volley request one time instead of writing repeatedly?

Hi friends i am developing an App for Student Database Management System.
Below is code to make request to server for each user service request and server sends response as in Json fromat.
LoginActivity.java
onCreate(){
requestQueue = Volley.newRequestQueue(context);
//making service method call here
JSONObject json = makeRequest(url,loginJson);
//printing response given by makeRequest() method
Log.e("std","-----------------Inside onCreate()----------------------" );
Log.e("std"," requested json "+json );
}
//////
public JSONObject makeRequest(String url, JSONObject jsonObject){
JSONObject myjson;
JsonObjectRequest myReq = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("std","-----------------Inside onResponse()----------------------" );
Log.e("std","response \n"+response);
myJson = new JSONObject(String.valueOf(response))
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//This code is executed if there is an error.
error.printStackTrace();
Log.e("error"," onErrorResponse "+error);
Toast.makeText(context,"Server Error...",Toast.LENGTH_SHORT).show();
}
}){
#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;
}
};
requestQueue.add(myReq);
return myJson;
}
inside onResponse listener i am getting my response as shown in bellow.
But makeRequest method returns me null JSON.
LogCat
com.example.stddbsystem E/std:-----------------Inside onResponse()----------------------
com.example.stddbsystem E/std:{"responseCode": 200,"responseMessage": "Login Success","userId": 1}
com.example.stddbsystem E/std:-----------------Inside onCreate()----------------------
com.example.stddbsystem E/std:requested json : null
Try this:
Change to:
#Override
public void onResponse(JSONObject response) {
myJson =response;
}
Instead of:
#Override
public void onResponse(JSONObject response) {
myJson = new JSONObject(String.valueOf(response))
}

How to use POST request in android Volley library with params and header?

I am trying to learn Volley library for posting data into webservices. I need to implement user registration form, following is the image of postman with parameters and header...
now problem is, i am getting below error
com.android.volley.ServerError
this is my code for volley post method.
public void postNewComment(){
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://myurl/api/users";
JSONObject jsonBody = new JSONObject();
jsonBody.put("email", "test1#gmail.com");
jsonBody.put("user_type", "C");
jsonBody.put("company_id", "0");
jsonBody.put("status", "A");
jsonBody.put("password", "123456");
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Log.e("VOLLEY", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
final Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Basic " + "My_auth_key");
headers.put("Content-Type", "application/json");
return headers;
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
please suggest where am i getting wrong. URL is working correct with postman, also as you can see i need to set 2 headers. I also tried this Url post method with AsyncTask and its working good. Now i need to implement this using volley library. kindly suggest. thank you.
this is my logcat error:
E/Volley: [81910] BasicNetwork.performRequest: Unexpected response code 405 for "Myurl"
**Try this one **
private void sendWorkPostRequest() {
try {
String URL = "";
JSONObject jsonBody = new JSONObject();
jsonBody.put("email", "abc#abc.com");
jsonBody.put("password", "");
jsonBody.put("user_type", "");
jsonBody.put("company_id", "");
jsonBody.put("status", "");
JsonObjectRequest jsonOblect = new JsonObjectRequest(Request.Method.POST, URL, jsonBody, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(), "Response: " + response.toString(), Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
onBackPressed();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
final Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Basic " + "c2FnYXJAa2FydHBheS5jb206cnMwM2UxQUp5RnQzNkQ5NDBxbjNmUDgzNVE3STAyNzI=");//put your token here
return headers;
}
};
VolleyApplication.getInstance().addToRequestQueue(jsonOblect);
} catch (JSONException e) {
e.printStackTrace();
}
// Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_LONG).show();
}
}
I have an alternative answer that works pretty well for Android Volley+ library by dworks and Google: See HERE

Volley onResponse method not working

I'm using Volley to send Post request.I'm trying to send jsonObject to server.This is my source
public void sendDicieIDToServer(JSONObject jsonObject)
{
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Log.e("response is", "Response " + jsonObject.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
NetworkResponse errorRes = volleyError.networkResponse;
String stringData = "";
if(errorRes != null && errorRes.data != null){
try {
stringData = new String(errorRes.data,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
Log.e("Error",stringData);
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Authorization",uhfScannerModel.getToken());
params.put("Content-Type", "application/json");
return params;
}
};
HandsetApplication.getInstance().addToRequestQueue(jsonObjectRequest);
}
I successfully created JsonObject and when I run my app and try to debug it, onErrorResponse method has called and stringData String contains real json result. I don't know what is a wrong and why onErrorResponse method calling.
User this link for Volley
Here i made volley reusability where you can apiCall easy way..
https://github.com/sikander-kh/Volley-Reusability

Android volley post methode parameter missing

I am using android volley library to post data to back-end service. But I can't send any parameter with my request. I have done each and everything mentioned here . But none works for me. The post method that I am using is:
public static void post()
{
// Tag used to cancel the request
String tag_json_obj = "json_obj_req";
String url = "http://myUrl";
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, obj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("TAG", "Error: " + error.getMessage());
}
}) {
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
return headers;
}
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("key", "value");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}
Always the response is "parameter missing".
How could i resolve this issue?
If you're using JSONObjectRequest, you can try this.
String url = "http://myurl";
Map<String, String> params = new HashMap<String, String>();
params.put("key", value);
RequestQueue queue = Volley.newRequestQueue(getActivity());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
url, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
try {
success = jsonObject.getInt("success");
message = jsonObject.getString("message");
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Activity activity = getActivity();
if (volleyError instanceof NoConnectionError) {
String errormsg = "Check your internet connection";
Toast.makeText(activity, errormsg, Toast.LENGTH_LONG).show();
}
}
});
queue.add(jsonObjectRequest);
The codes are more likely the same as yours. Check on the lines where I put the data to be posted. I'm very sure this would work!
The problem is you are approaching the request as though you were making a stringRequest. The link you reference is talking specifically about making a stringRequest.
jsonObjectRequest actually lets you put the json object into the constructor itself, instead of using the override method getParams() like so:
String url = "some_url";
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put(Constants.LOGIN_EMAIL_ID, email);
jsonObject.put(Constants.LOGIN_PASSWORD, password);
}catch(JSONException e){
Log.d("JSON error", e.getMessage(), e);
}
JsonObjectRequest jsObjRequest = new JsonObjectRequest(url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("RESPONSE", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(error.getMessage()!=null){
Log.d("RESPONSE", error.getMessage());
}
}
});
VolleySingleton.getInstance(activity).getRequestQueue().add(jsObjRequest);

Categories

Resources