I've tried with normal JSONArrayRequests and StringRequests and everything was fine untill now. I want to send an JSONArrayRequest with POST parameters to get some MySQL result in JSON format from the script. Unfortunately I get [] everytime in response. I have checked .php file and query with _GET method and the script worked perfectly returning desired rows in Json format.
I read here (https://stackoverflow.com/a/18052417/4959185) Volley Team have added JSONArrayRequest with _POST parameter to their class. However it does not work in my case. Could you please look what is wrong with that function:
private void getFavouriteRecipes(final String userUniqueId, final int offset) {
JsonArrayRequest favouriteRecipesReq = new JsonArrayRequest(Request.Method.POST,
AppConfig.URL_GETFAVOURITERECIPES, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("odpowiedz", "Odpowiedź ulubionych: " + response);
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jObj = response.getJSONObject(i);
RecipeItem recipeItem = new RecipeItem();
recipeItem.setRecipeUniqueID(jObj.getString("unique_id"));
recipeItem.setRecipeTitle(jObj.getString("title"));
recipeItem.setRecipeImgThumbnailLink(jObj.getString(
"img_tumbnail_link"));
recipeItem.setRecipeAddAte(jObj.getString("add_date"));
recipeItem.setRecipeKitchenType(jObj.getString("kitchen_type"));
recipeItem.setRecipeMealType(jObj.getString("meal_type"));
recipeItem.setRecipeName(jObj.getString("name"));
recipeItem.setRecipeSurname(jObj.getString("surname"));
recipeItem.setRecipeLikeCount(jObj.getString("like_count"));
recipeFavouriteItems.add(recipeItem);
} catch (JSONException e) {
e.printStackTrace();
showSnackbarInfo("Błąd Json: " + e.getMessage(),
R.color.snackbar_error_msg);
}
}
recipeFavouriteItemsAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("odpowiedz", "Błąd pobierania ulubionych: " +
Integer.toString(error.networkResponse.statusCode));
showSnackbarInfo(Integer.toString(error.networkResponse.statusCode),
R.color.snackbar_error_msg);
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting Parameters to Login URL
Map<String, String> params = new HashMap<>();
params.put("user_unique_id", userUniqueId);
params.put("offset", Integer.toString(offset));
Log.d(TAG, "wysylam parametry: " + userUniqueId + ", " + Integer.toString(offset));
return params;
}
};
// Adding Request to Request Queue
AppController.getInstance().addToRequestQueue(favouriteRecipesReq);
}
My PHP Script:
https://ideone.com/ZxYzHr
I have found another way to get JSONArrayResponse with sending parameters. I think that will help somebody.
U just write standard JSONArrayRequest liek this:
JsonArrayRequest favouriteRecipesReq = new JsonArrayRequest(prepareGetMethodUrl(),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("odpowiedz", "Odpowiedź ulubionych: " + response.toString());
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jObj = response.getJSONObject(i);
RecipeItem recipeItem = new RecipeItem();
recipeItem.setRecipeUniqueID(jObj.getString("unique_id"));
recipeItem.setRecipeTitle(jObj.getString("title"));
recipeItem.setRecipeImgThumbnailLink(jObj.getString(
"img_tumbnail_link"));
recipeItem.setRecipeAddAte(jObj.getString("add_date"));
recipeItem.setRecipeKitchenType(jObj.getString("kitchen_type"));
recipeItem.setRecipeMealType(jObj.getString("meal_type"));
recipeItem.setRecipeName(jObj.getString("name"));
recipeItem.setRecipeSurname(jObj.getString("surname"));
recipeItem.setRecipeLikeCount(jObj.getString("like_count"));
recipeFavouriteItems.add(recipeItem);
} catch (JSONException e) {
e.printStackTrace();
}
}
recipeFavouriteItemsAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("odpowiedz", "Błąd pobierania ulubionych: " +
Integer.toString(error.networkResponse.statusCode));
showSnackbarInfo(Integer.toString(error.networkResponse.statusCode),
R.color.snackbar_error_msg);
}
});
// Adding Request to Request Queue
AppController.getInstance().addToRequestQueue(favouriteRecipesReq);
Instead of standard URL to the PHP script I inserted function returning String called prepareGetMethodUrl().
Let's look inside it:
private String prepareGetMethodUrl() {
return AppConfig.URL_GETFAVOURITERECIPES + "?user_unique_id=" + userUniqueId + "&offset=" +
Integer.toString(offset);
}
As you can see it's very simple. I get standard AppConfig.URL_GETFAVOURITERECIPES which is static field in AppConfig class conatining direct link to my PHP script on my serwer f.e http://www.someserversite.com/my_api/gmy_php_script.php and combine it with parametres values I need to send to the script: user_unique_id and it's content userUniqueId and offset which content is offset parsed from int to String.
Inside my script I just call:
<?php
// some code
// Receiving The Post Params
$user_unique_id = $_GET['user_unique_id'];
$offset = $_GET['offset'];
echo $user_unique_id . "<br />";
echo $offset;
?>
Related
I know this question has been asked a few times and i have tried all the solutions however, nothing seems to work. My method:
public static LocationGeoData getLocationGeoData(Location location){
RequestQueue requestQueue = Volley.newRequestQueue(MyApplication.getAppContext());
Date dateNow = new Date();
SimpleDateFormat fmt = new SimpleDateFormat("yyyy.MM.dd");
String url = "MYCORRECTURL";
Log.d("geoData", "In getGeoData " + url); // this is called and logs
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("geoData", "inside the response");// this never gets called
try {
JSONObject jsonObject = response.getJSONObject("data");
for(int i = 0; i <jsonObject.length(); i++){
JSONObject heading = jsonObject;
if(heading.getString("field-value").equals("field-value")){
JSONObject totIntensity = heading.getJSONObject("total-intensity");
JSONObject declination = heading.getJSONObject("declination");
JSONObject inclination = heading.getJSONObject("inclination");
int totalIntensity = totIntensity.getInt("value");
double declinationValue = declination.getDouble("value");
double inclinationValue = inclination.getDouble("value");
locationGeoData = new LocationGeoData(totalIntensity, declinationValue, inclinationValue);
}
}
} catch (JSONException e) {
Log.d("geoData", "Error recorded");//never called
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("geoData", "Error recorded");// never called
}
});
requestQueue.add(request);
return locationGeoData;
}
The second Log message inside the response never gets called, i get no error messages, my url works and i can see the JsonOBject in the browser when tested, but the response is never called in my method. Can anyone advise me what i am doing wrong?
I have the following URL: http://localhost:3000/api/bodega/list?valor=Bodega GENERAL ,
when testing it using postman it works correctly and brings me the data. But now I'm trying to do it using volley with the following code
RequestQueue queue = Volley.newRequestQueue(this);
String Ruta = null;
//URL para realizar la peticion
Ruta = V_URL_MON + "/api/bodega/list?valor=" + "Bodega GENERAL";
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, Ruta, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
for(int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
recuperarID = jsonObject.getString("_id");
}
catch(JSONException e) {
}
}
Variables_Globales.BODEGA_ORIGEN = recuperarID;
}
} ,
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(Crear_Traslado.this, "Unable to fetch data: " + volleyError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
queue.add(request);
It is generating an error Unable to fetch data: null, doing tests I realized that the error is caused by the URL "/api/bodega/list?valor=" + "Bodega GENERAL", specifically in "Bodega GENERAL", because if I remove the space it works correctly
I'm really new on android and I'm wokring on a login system, I'm using volley to post the data....the problem thatm I'm having is when i try to read the response....
the response looks like this:
{"st":"no","Message":"Error"}
I'm trying to access only st or message is there a way to do that ? I tried doing:
response[i] ----Array type expexted found ' org.json.JSONObject'
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, url, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Response: " + response.length());
for (int i = 0; i < response.length(); i++) {
Log.e(TAG, "Values: " + response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
Volley.newRequestQueue(this).add(jsonRequest);
You could use
response.getString("Message")
to get a message from given JSON
#Override
public void onResponse(String response) {
try {
JSONObject api_response = new JSONObject(response);
String message = api_response.getString("Message")
} catch (JSONException e) {
e.printStackTrace();
}
Its important to catch the json exception just in case the response string cannot be converted to json object. Then use the getString() to get the message from the created json object.
This question may look like a duplicate(it is NOT), but I am stuck with this JSONException error:
Value die of type java.lang.String cannot be converted to JSONArray.
I'm using JsonArrayRequest of Volley to get jsonarray from a server. My JsonArrayRequest is throwing the above error, as i want to post a string to the server and receive jsonarray as a response. Below is my code:
JsonArrayRequest jsonReq = new JsonArrayRequest(Request.Method.POST,
URL, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject JO = response.getJSONObject(i);
GetterSetter getterSetter = new GetterSetter();
getterSetter.setName(JO.getString("name"));
getterSetter.setNumber(JO.getString("number"));
getterSetter.setDate(JO.getString("date"));
myList.add(getterSetter);
} catch (JSONException e) {
e.printStackTrace();
}
}
myAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("myKey", myValue);
return params;
}
};
MySingleton.getInstance().addToRequestQueue(jsonReq);
}
The PHP file is working properly and it is passing json string to android.
The error is happening somewhere within onResponse block. The same block works clean when using StringRequest instead of JsonArrayRequest.
Any idea what exactly is causing this error? Any help or guidance is much appreciated.
* I'm new in Android Volley and the way it works.
EDIT
This is a format/syntax of the url response:
[
{"name":"test",
"number":"123",
"date":"2017-08-22"
},
{"name":"test1",
"number":"1234",
"date":"2017-08-23"
}
]
Try using StringRequest and then create your own JSONArray from the response string:
new JSONArray(response);
You can find example StringRequest from the documentation:
Sending a Simple Request
I'm always getting the following error as long as i put a array into Params. Even after converting to String it still gives that error. The code works fine without the contactlist array inside it. Any idea?
Error
com.android.volley.ParseError: org.json.JSONException: Value Created
of type java.lang.String cannot be converted to JSONObject
Sample response:
{
"username": "test2",
"lists": [
"contact_0",
"contact_1",
"contact_2",
"contact_3",
"contact_4",
"contact_5",
"contact_6",
"contact_7",
"contact_8",
"contact_9"
]
}
ArrayList<String> contactList = new ArrayList<String>();
public String joinInfo;
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println("name : " + name + ", ID : " + phoneNumber);
joinInfo = name;
contactList.add(joinInfo);
}
phones.close();
RequestQueue rq = Volley.newRequestQueue(this);
JSONObject params = new JSONObject();
try {
params.put("username", "test2");
params.put("lists", contactList.toString()); // When i change this to simply "test" a string, it works fine.
Log.d("PANDA", contactList.toString());
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
"http://postcatcher.in/catchers/55521f03f708be0300001d28", params, //Not null.
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("PANDA", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("PANDA", "Error: " + error.getMessage());
Log.d("PANDA", error.toString());
}
});
// Adding request to request queue
rq.add(jsonObjReq);
PostCatcher although allowing us to post requests, its response is basically a plain string "Created" and not in Json format. As such our client code is not able to ascertain it and throws error. One thing is even without ArrayList object that is with plain (String, String) K,V pair also it would fail.
You can verify it if you try sending request through Advanced Rest Client (see attached)