How can I do this Get on volley? - java

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

Related

How to send JSONArray to PHP server using Volley?

I'm fairly inexperienced with Android programming and am having issues sending a JSONArray to my PHP server. I am using the following code to generate the JSONArray from my cursor:
public JSONArray matrixJSON(){
Cursor cursor = db.rawQuery("SELECT columnID,rowID,value FROM Matrix WHERE PolicyID=" + curPolicy,null);
JSONArray resultSet = new JSONArray();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
int totalColumn = cursor.getColumnCount();
JSONObject rowObject = new JSONObject();
for (int i = 0; i < totalColumn; i++) {
if (cursor.getColumnName(i) != null) {
try {
rowObject.put(cursor.getColumnName(i),
cursor.getString(i));
} catch (Exception e) {
Log.d(TAG, e.getMessage());
}
}
}
resultSet.put(rowObject);
cursor.moveToNext();
}
cursor.close();
return resultSet;
}
I believe I am misunderstanding how to properly send data via JsonARrayRequest. Here is the following code that I am using to send the data.
public void sendData(JSONArray data) {
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://10.123.20.180:8080/insertmatrix.php";
JsonArrayRequest dataReq = new JsonArrayRequest(Request.Method.POST, url, data,
response -> Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_LONG).show(),
error -> Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show()){
#Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
if (response.data == null || response.data.length == 0) {
return Response.success(null, HttpHeaderParser.parseCacheHeaders(response));
} else {
return super.parseNetworkResponse(response);
}
}
};
queue.add(dataReq);
}
Instead of sending the data, I am left with a blank array. The cursor to JSONarray function is working properly as I can see in debug, but the php server is receiving a blank array. I assume there is some essential functions I am missing.
Fixed it by switching my array into a string and then using a StringRequest to send the data.
Updated function:
public void sendData(JSONArray data) {
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://10.123.20.180:8080/insertmatrix.php";
String json = data.toString();
StringRequest dataReq = new StringRequest(Request.Method.POST,url,response -> Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_LONG).show(),
error -> Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show()){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String,String>();
params.put("data",json);
return params;
}
};
queue.add(dataReq);
}

Android Volley get request, my onResponse never gets called

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?

How to read response from a POST volley?

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.

Volley JSONArrayRequest - not sending params properly?

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

Volley ui freeze on parsing data

I'm using this code for sending data to server , but when i want to parser response data on volley onResponse method , my UI freezing .
JsonObjectRequest req = new JsonObjectRequest(Method.GET, url, null, new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
parseFromJsonObject(response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
}
});
RequestHelper.getInstance().addToRequestQueue(req, this);
And it's parser method
public boolean parseFromJsonObject(JSONObject response)
{
boolean validResponse = super.isValidResponse(response);
try
{
if(response.has("keywords"))
{
JSONObject keywords = response.getJSONObject("keywords");
Iterator<?> langIterator = keywords.keys();
ArrayList<LanguagesStorage> languagesStorageArray = new ArrayList<LanguagesStorage>();
while(langIterator.hasNext())
{
String lang = (String) langIterator.next();
JSONObject langValues = keywords.getJSONObject(lang);
Iterator<?> valueIterator = langValues.keys();
while(valueIterator.hasNext())
{
String key = (String) valueIterator.next();
String value = (String) langValues.getString(key);
LanguagesStorage languagesStorage = new LanguagesStorage();
languagesStorage.setKey(key);
languagesStorage.setLang(lang);
languagesStorage.setValue(value);
languagesStorageArray.add(languagesStorage);
}
}
if(languagesStorageArray.size() > 0)
{
LanguageAdapter languageAdapter = new LanguageAdapter();
languageAdapter.insert(languagesStorageArray, true);
}
}
return lastParsingStatus = true;
}
catch (JSONException e)
{
RLog.error("Parsing error in keyword Parser " + e);
return lastParsingStatus = false;
}
}
What is the issue ? Why my UI thread freezing?
Volley onResponce work inside the UI thread
I recommend you to do parsing inside a separate thread.
In your parseFromJsonObject method, try to create a new Thread and inside that thread execute your parsing data.

Categories

Resources