Android Volley - JsonArrayRequest with post parameters - android

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

Related

How to solve Error in json parsing using volley POST?

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

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

Send token header in json object paramater Volley post

I am using post method in volley. I searched and found that getHeader() is used to send header in request.The solution was to use JSONObject request instead of string request(which i am using currently) but is there a way of sending header through this method? Because in that case I will have to modify a lot of code in many classes. Sorry for the English, I am not a native speaker.
The request parameter is a json object. I am sending the parameters using following code.
mRequestQueue = Volley.newRequestQueue(getContext());
mStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response", "onResponse: " + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("This is the error", "Error :" + error.toString());
}
})
{
#Override
public String getBodyContentType() {
return "application/json";
}
#Override
public byte[] getBody() throws AuthFailureError {
HashMap<String, String> params2 = new HashMap<String, String>();
params2.put("AssigneeId",userid);
params2.put("IssueStatus", "5");
return new JSONObject(params2).toString().getBytes();
}
};
mRequestQueue.add(mStringRequest);
This request also has StringRequest. Please use the getHeaders() in this way:
public void requestWithSomeHttpHeaders() {
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://www.somewebsite.com";
StringRequest getRequest = new StringRequest(Request.Method.GET, 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) {
// TODO Auto-generated method stub
Log.d("ERROR","error => "+error.toString());
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("User-Agent", "Nintendo Gameboy");
params.put("Accept-Language", "fr");
return params;
}
};
queue.add(getRequest);
}
For JsonObjectRequest:
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,url,
null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(tag, response.toString());
activity.hideDialog();
try {
activity.onRequestServed(response, code);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(tag, "Error: " + error.getMessage());
Log.e(tag, "Site Info Error: " + error.getMessage());
Toast.makeText(activity.getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
activity.hideDialog();
try {
activity.onRequestServed(null,code);
} catch (JSONException e) {
e.printStackTrace();
}
}
}) {
/**
* Passing some request headers
*/
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
//headers.put("Content-Type", "application/json");
headers.put("key", "Value");
return headers;
}
};

Android volley is not sending params

The code which does not work is below. See anything wrong with this code , why it is not sending parameters. I am new to Android.
private void sendParams()
{
JsonArrayRequest movieReq = new JsonArrayRequest(AppConfig.URL_Q_RECIPIES,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Recipie movie = new Recipie();
movie.setRecipieName(obj.getString("recipie_name"));
movie.setId(obj.getInt("id"));
// build the image URL here
String s = AppConfig.URL_IMAGE + obj.getInt("id") + ".jpeg";
movie.setImageURL(s);
movie.setPrimaryIngrediant(obj.getString("prim_ingr"));
movie.setUrl(obj.getString("url"));
// adding movie to movies array movie is nothing but recipie
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Filter error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hidePDialog();
}
}) {
#Override
protected Map<String, String> getParams () {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("ind_ajwain", Integer.toString(session.isAjwainChecked()));
//params.put("ind_asaftide", Integer.toString(session.isAsaftideChecked()));
params.put("rec_name", "chicken"); /// change this
params.put("ind_ginger", "0");
//params.put("password", password);
return params;
}
};
Log.d(TAG, movieReq.toString());
//movieReq.
AppController.getInstance().addToRequestQueue(movieReq);
}
I followed this link to get coding don : Source: https://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/
I have not made much changes above, only changing parameters.
For sending data to server using Volley refer below code.
Step1 : Use POST method to send data.
Create below method :
private void makeJsonSend() {
StringRequest jsonObjReq = new StringRequest(Request.Method.POST,Const.ServiceType.URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("response:forgot", response);
jsonParseResponse(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//show error message here
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("email","email");
//pass parameter here
Log.i("request send data", params.toString());
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
//If you have header parameter then set here
return headers;
}
};
AppController.getInstance().addToRequestQueue(movieReq);
}
Step 2: Response method where you have get response of that operation.
private void jsonParseResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString("status").equals("200")) {
cc.showToast(jsonObject.getString("message"));
} else {
cc.showToast(jsonObject.getString("message"));
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("Forgot Error",e.toString());
}
}
You didn't pass any request method in new JsonArrayRequest. You have to pass Request.Method.POST or Request.Method.GET

Listview not inflating with json

i have to inflate listview with the Json data with parameters . But it gives error 2.onErrorResponse: MainActivity . I checked multiple times with String Request and Json Request but none of them is working... Please Help!!!
JsonArrayRequest movieReq = new JsonArrayRequest(Request.Method.POST,url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
title_array.add(obj.getString("amount").toString());
notice_array.add(obj.getString("payment_id").toString());
title1_array.add(obj.getString("invoice_id").toString());
notice1_array.add(obj.getString("payment_date").toString());
notice2_array.add(obj.getString("movieName").toString());
notice3_array.add(obj.getString("source").toString());
adapter = new CustomBaseAdapter(Transaction.this, title_array, notice_array,title1_array,notice1_array,notice2_array,notice3_array);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
}){
#Override
protected Map<String, String> getParams()
throws com.android.volley.AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("user_id", user_id);
params.put("user_type", User_type);
return params;
}
};
// Adding request to request queue
requestQueue.add(movieReq);

Categories

Resources