How to solve Error in json parsing using volley POST? - android

Hi I am using volley as JSON Parsing. I am using POST method and sending parameters in post request. I am getting following error when parsing the data, I am getting following error. I want to use volley. I have tried with JsonArrayRequest but it does not allow to send parameters as JSONObject,which I am using in my code.
org.json.JSONArray cannot be converted to JSONObject
Request is like
{
"city":"acd",
"user_id":"82",
"phone_number1":"1232131231",
"my_type":"asf"
}
Response is like
[{
"name":"dfdfd",
}]
Following is my code
private void Search_Refer() {
//initialize the progress dialog and show it
progressDialog = new ProgressDialog(SearchReferNameActivity.this);
progressDialog.setMessage("Please wait....");
progressDialog.show();
try {
JSONObject jsonBody = new JSONObject();
jsonBody.put("city", "acb");
jsonBody.put("user_id", "82");
jsonBody.put("phone_number1", "12332123231");
jsonBody.put("my_type", "asf");
JsonObjectRequest jsonOblect = new JsonObjectRequest(Request.Method.POST, Constants.BASE_URL1+"api/lab/search", jsonBody, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
Log.e("Search EROOR", response.toString());
try {
JSONArray itemArray=new JSONArray(response);
dataModelArrayList = new ArrayList<>();
for (int i = 0; i < itemArray.length(); i++) {
SearchModel playerModel = new SearchModel();
JSONObject dataobj = itemArray.getJSONObject(i);
//playerModel.setProduct_name(dataobj.getString("name"));
playerModel.setRadiology_store_first_name(dataobj.getString("radiology_store_first_name"));
dataModelArrayList.add(playerModel);
}
} catch (JSONException e) {
e.printStackTrace();
}
progressDialog.dismiss();
/* Intent intent = new Intent(SearchReferNameActivity.this, SearchResult.class);
intent.putExtra("Search_result", dataModelArrayList);
startActivity(intent);*/
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Response: " + error.toString(), Toast.LENGTH_SHORT).show();
System.out.println("Search Eroor"+error.toString());
progressDialog.dismiss();
}
}){
#Override
public String getBodyContentType() {
return "application/json";
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", "Bearer "+deviceToken);
return headers;
}
};
jsonOblect.setRetryPolicy(new DefaultRetryPolicy(
10000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MyApplication.getInstance().addToRequestQueue(jsonOblect,"postrequest");
} catch (JSONException e) {
e.printStackTrace();
}
// Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_LONG).show();
}

Use JsonArrayRequest or StringRequest in place of JsonObjectRequest
JsonArrayRequest

change the following response parameter to JSONArray
Instead of new Response.Listener<JSONObject> Use new Response.Listener<JSONArray>
// JSONArray insated of JSONObject
public void onResponse(JSONArray response) {
}

Use Below code
StringRequest stringRequest = new StringRequest(Request.Method.POST, "api/lab/search", new Response.Listener<String>() {
#Override
public void onResponse(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("city", "abcd");
params.put("user_id", "82");
params.put("phone_number1", "01235467895");
params.put("my_type", "asf");
return params;
}
};

Related

How to make android Volley request with body like following

I have following request in postman and I want to implement it in volley, android.
Any solution?
following is request header
Following is request body
Do like this .Add headers data like this.
RequestQueue queue = Volley.newRequestQueue(this);
String url = APICLient.BASE_URL+"api/Admin_controller/getProspectField";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jo=new JSONObject(response);
Boolean status=jo.getBoolean("success");
JSONArray ja=jo.getJSONArray("user");
// write your logic here...
for (int i=0;i<ja.length();i++){
JSONObject jsonObject=ja.getJSONObject(i);
String pname=jsonObject.getString("p_name");
String pType=jsonObject.getString("p_type");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}) {
#Override
public Map<String, String> getHeaders(){
HashMap <String,String> params=new HashMap<>();
params.put("authorization","put_authorization_key_here");
return params;
}
#Override
public Map<String, String> getParams(){
HashMap <String,String> params=new HashMap<>();
params.put("care_team[]",team);
........................
return params;
}
};
queue.add(stringRequest);
Hope this will work.
Json Parsing with volley:
private void userLogin() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting response to json object
JSONObject obj = new JSONObject(response);
//if no error in response
if (obj.getBoolean("status")) {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
//getting the user from the response
JSONObject userJson = obj.getJSONObject("user");
//creating a new user object
User user = new User(
userJson.getInt("cid"),
userJson.getInt("company_id"),
userJson.getString("name"),
userJson.getString("email")
);
//storing the user in shared preferences
SharedPreferenceManager.getInstance(getApplicationContext()).userLogin(user);
//starting the profile activity
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
} else {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
} catch (JSONException e) {
e.printStackTrace();
progressBar.setVisibility(View.GONE);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("company_id",companyid );
params.put("email", username);
params.put("password", password);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("x-api-key", "swicons#1019");
return headers;
}
};
stringRequest.setShouldCache(false);
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
}

How do i send body data with a JsonObjectRequest? Android-Volley library

I am trying to send data to my server. I create a JsonObject and I pass it as a parameter when creating the JsonObjectRequest. It doesn't give any error, but it is not returning anything. Tried with postman and it is working fine.
This is my code:
JSONObject jsonBody = new JSONObject();
try {
jsonBody.put("firstname", "asd");
jsonBody.put("lastname", "asd");
jsonBody.put("id", "1");
} catch (JSONException e) {
e.printStackTrace();
}
//creating a JsonObjectRequest
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, showPlayersUrl,
jsonBody, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONArray players;
try{
players = response.getJSONArray("Players");
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
}
Ok, found the problem. Server side i wasn't accepting the data as json format. Just had to add this and it works:
$_POST = json_decode(file_get_contents('php://input'), true);
Try it:
RequestQueue queue = Volley.newRequestQueue(this);
private void makeJsonObjReq() {
showProgressDialog();
Map<String, String> postParam= new HashMap<String, String>();
postParam.put("un", "xyz#gmail.com");
postParam.put("p", "somepasswordhere");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
Const.URL_LOGIN, new JSONObject(postParam),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideProgressDialog();
}
}) {
#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;
}
};
jsonObjReq.setTag(TAG);
queue.add(jsonObjReq);
}

Volley GET with parameters

I have a web service which gives data in JSON array format. Right now the data is being fetched just by passing the URL. But now I want to pass a parameter to get the JSON response. This web service has GET & POST methods.
I tried with Volley - Sending a POST request using JSONArrayRequest answer, but I couldn't implement it in my code. It would be really helpful if somebody could explain, how to achieve this in my code.
This is how my code looks like
String HTTP_SERVER_URL = "https://192.168.1.7/STUDENTWS/Default.asmx/StudentDataJson?InFacultyID=string";
public void JSON_WEB_CALL(){
//mSwipeRefreshLayout.setRefreshing(true);
jsonArrayRequest = new JsonArrayRequest(HTTP_SERVER_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
DataModel GetDataModel = new DataModel();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataModel.setId(json.getString("STUDENTID"));
GetDataModel.setPlateNo(json.getString("GRADE"));
GetDataModel.setPlateCode(json.getString("HOUSE"));
}
catch (JSONException e)
{
e.printStackTrace();
}
DataAdapterClassList.add(GetDataModel);
mSwipeRefreshLayout.setRefreshing(false);
}
recyclerViewadapter = new NewRecyclerViewAdapter(DataAdapterClassList, this);
recyclerView.setAdapter(recyclerViewadapter);
if (array.length()!=0) {
SHOW_ALERT(array);
sendNotification(recyclerView, array);
}
}
For get with params you should create StringRequest. For example:
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest sr = new StringRequest(Request.Method.GET, "http://headers.jsontest.com/",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("HttpClient", "success! response: " + response.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("HttpClient", "error: " + error.toString());
}
})
{
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("user","YOUR USERNAME");
params.put("pass","YOUR PASSWORD");
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;
}
};
// for json object
Map<String, String> jsonParams = new HashMap<String, String>();
jsonParams.put("fullname",fullName);
jsonParams.put("email",email);
jsonParams.put("password",password);
// for json array make any list.List will be converted to jsonArray
// example-----
// ArrayList<String> jsonParams =new ArrayList();
// jsonParams.add("Test1")
// jsonParams.add("Test2")
JsonObjectRequest objectRequest=new JsonObjectRequest(Request.Method.POST, url, new JSONObject(jsonParams), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "onErrorResponse: ",error );
Toast.makeText(ActivitySignUp.this,error.getMessage(), Toast.LENGTH_LONG).show();
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String,String> header=new HashMap<String, String>();
header.put("Content-Type","application/json");
return header;
}
};
If you want to pass a param to your server, then you might wanna do a POST method, else.. if you only wanted to get the data, then GET method is the best way... there's also header that you can use to pass data, but, I wouldn't recommend to use header for sending params... that's a sore eyes
Edit
//Set you method POST or GET
JsonObjectRequest(Request.Method.GET(/*here can set to POST too*/), url, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
// display response
Log.d("Response", response.toString());
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", response);
}
}
);

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);

Android Volley - JsonArrayRequest with post parameters

I'm using Volley to interact with an API. I need to send a post request with parameters to a service that returns a JSONArray.
I'm overriding the method protected Map<String, String> getParams() but it is not working:
JsonArrayRequest eventoReq = new JsonArrayRequest(Configuracion.URL_API_PROXIMOS_EVENTOS,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsea json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Evento evento = new Evento();
evento.setCod_evento(obj.getInt("cod_evento"));
evento.setTitulo(obj.getString("titulo"));
evento.setDescripcion(obj.getString("descripcion"));
evento.setDireccion(obj.getString("direccion"));
evento.setImagen(obj.getString("imagen"));
evento.setPuntuacion((float) obj.getDouble("puntuacion"));
// Añade el evento al listado
listaEventos.add(evento);
} catch (JSONException e) {
e.printStackTrace();
}
}
// Actualiza el adaptador
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
}){
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "eventos_proximos_usuario");
params.put("cod_usuario", cod_usuario);
return params;
}
#Override
public int getMethod() {
return Method.POST;
}
};
// Añade la peticion a la cola
AppController.getInstance().addToRequestQueue(eventoReq);
Try ...
StringRequest instead..
Reference:
https://android.googlesource.com/platform/frameworks/volley/+/master/src/main/java/com/android/volley/toolbox
JsonObjectRequest extends JsonRequest
whereas StringRequest extends Request
StringRequest eventoReq = new StringRequest(Request.Method.POST,Configuracion.URL_API_PROXIMOS_EVENTOS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
hidePDialog();
try{
JSONArray j= new JSONArray(response);
// Parsea json
for (int i = 0; i < j.length(); i++) {
try {
JSONObject obj = j.getJSONObject(i);
Evento evento = new Evento();
evento.setCod_evento(obj.getInt("cod_evento"));
evento.setTitulo(obj.getString("titulo"));
evento.setDescripcion(obj.getString("descripcion"));
evento.setDireccion(obj.getString("direccion"));
evento.setImagen(obj.getString("imagen"));
evento.setPuntuacion((float) obj.getDouble("puntuacion"));
// Añade el evento al listado
listaEventos.add(evento);
} catch (JSONException e) {
e.printStackTrace();
}
}
// Actualiza el adaptador
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
}){
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "eventos_proximos_usuario");
params.put("cod_usuario", cod_usuario);
return params;
}
};
// Añade la peticion a la cola
AppController.getInstance().addToRequestQueue(eventoReq);
Me just a beginner hope it helps!!!
try like this,
I think you don't need to override the getMethod() method.
Pass the method type (i.e Method.POST) name with in the JsonObjectRequest or JsonArrayRequest like below.
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
pDialog.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
pDialog.hide();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "eventos_proximos_usuario");
params.put("cod_usuario", cod_usuario);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
I faced the same problem when I started to use Volley in my android project. I solved the problem by using StringRequest instead of JsonArrayRequest.
for example if you want to show a ListView with some server data...
Just use a simple StringRequest instead of JSONArrayRequest and implements the onResponse Methode like this :
public void onResponse(String response){
try{
JSONArray jsonArray=new JSONArray(response);
for(int i=0;i<jsonArray.length();i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// do something
} catch (JSONException e) {
e.printStackTrace();
}
}
}catch (JSONException e2){
e2.printStackTrace();
}
}
}
StringRequest request = new StringRequest(Request.Method.POST, YourUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (!response.equals(null)) {
Log.e("Your Array Response", response);
} else {
Log.e("Your Array Response", "Data Null");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error is ", "" + error);
}
}) {
//This is for Headers If You Needed
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json; charset=UTF-8");
params.put("token", ACCESS_TOKEN);
return params;
}
//Pass Your Parameters here
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("User", UserName);
params.put("Pass", PassWord);
return params;
}
};
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
queue.add(request);

Categories

Resources