Parsing JSONArray using Gson + Volley not getting response - java

So I am trying to parse an array of objects from json using Google's Gson library and Volley for HTTP requests. My issue is it's as if the code isn't 'hitting' the OnResponse call. I've tried adding a simple Log printout within the function just to see if it does anything.
My GsonRequest class comes straight from Google's Training Docs. I constructed these methods based on an answer to this question.
This is my code:
private void runVolleyJson() throws AuthFailureError {
GsonRequest<Meetings> getMeetings = new GsonRequest<Meetings>(AUTH_URL, Meetings.class, getHeaders(),
createMyReqSuccessListener(),
createMyReqErrorListener());
helper.add(getMeetings);
}
private Response.Listener<Meetings> createMyReqSuccessListener() {
return new Response.Listener<Meetings>() {
#Override
public void onResponse(Meetings response) {
// NOTHING HAPPENS FROM HERE!
try {
Log.d("response", response.toString());
} catch (Exception e) {
e.printStackTrace();
}
// Do whatever you want to do with response;
// Like response.tags.getListing_count(); etc. etc.
}
};
}
private Response.ErrorListener createMyReqErrorListener() {
return new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Do whatever you want to do with error.getMessage();
}
};
}
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> map = new HashMap<>();
map.put("Content-Type", "application/json;");
map.put("Authorization", "Bearer <sometoken>");
return map;
}
There is absolutely no error. It is authorizing the request, but nothing happens in OnResponse, it just seems to ignore that function.
Now I've tried using a standard StringRequest with volley and it works flawlessly, like this:
private void runVolleyTest() {
StringRequest request = new StringRequest(Request.Method.GET, AUTH_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonarray = new JSONArray(response);
for(int i = 0; i < jsonarray.length(); i++) {
Gson gson = new Gson();
Meeting m = gson.fromJson(jsonarray.get(i).toString(), Meeting.class);
Log.e("Meeting", m.getMeetingId() + " " + m.getStatus());
}
} catch (JSONException e) {
e.printStackTrace();
}
;
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
txtError(error);
}
}) {
#Override
public Map<String, String> getHeaders() {
HashMap<String, String> map = new HashMap<>();
map.put("Content-Type", "application/json;");
map.put("Authorization", "Bearer <sometoken>");
return map;
}
};
//request.setPriority(Request.Priority.HIGH);
helper.add(request);
}

Try adding this line at the beginning
RequestQueue helper = Volley.newRequestQueue(mContext);

Add these line
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
if you don't want to the save response in cache memory then add this
requestQueue.add(stringRequest);
According to my personal opinion its better if you pass the application context.

Related

Is it possible to get a response as a json file instead of making him a jsonobject in java?

So i have a get request from an API, when i get the response i want to make that response into a json file instead of making him an JSONOBJECT, is it possible ? i will paste the get funcion here, and the way im getting the JSONOBJECT.
I want to replace the way i get a JSONOBJECT, from a way to get that json as a file that goes to my assets directory.
public void getAssetPlant(final VolleyCallBack callBack) {
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.GET, url_assets, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject j = new JSONObject(response);
callBack.onSuccess();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MapActivity.this, "Failed to gather info" + error.networkResponse.statusCode, Toast.LENGTH_SHORT).show();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Bearer " + token);
return headers;
}
};
requestQueue.add(request);
}

How do I read header from Volley request's JSON response?

I am developing an application where Logging In returns a cookie named "authCookie" from server and this cookie is in header of the response. I am using Volley library and String Request for server-mobile application communication. Can you please guide me how do I get this cookie from header?
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
if(obj.has("csrf") && obj.has("refreshToken")){
csrf = obj.getString("csrf");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null){
if(error.networkResponse.statusCode == 400){
Toast.makeText(MainActivity.this,"Invalid username/password",Toast.LENGTH_LONG).show();
}
}
else{
Toast.makeText(MainActivity.this,"Check internet connection!",Toast.LENGTH_LONG).show();
}
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("username", username);
params.put("password", password);
return params;
}
};
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
I want authCookie from response and save it in a string.

Android-volley: how do I take the String response value and assign it outside of a volley StringRequest method?

The data appears as expected when I run the method in the debugger, however whenever I try to do anything with it the value of parentObject is returned as null.
I simply want to take the response from the server and store it as a JSONObject to be reused elsewhere.
public void jsonParse() {
String url = "http://178.128.166.68/getUserInfo.php";
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
/*
the data appears as expected within the debugger however
returns null when i attempt to use it elsewhere
*/
parentObject = new JSONArray(response);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("phone", phone);
params.put("password", password);
return params;
}
};
mQueue.add(request);
}
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
parentObject = new JSONArray(obj);
for (int i = 0; i < parentObject.length(); i++) {
JSONObject parObj = (JSONObject) parArray.get(i);
ModelClass modelClass = new ModelClass()// you have to create a model
modelClass.set1Parameter(parObj.getString("1Parameter"));
modelClass.set2Parameter(parObj.getString("2Parameter"));
arrayList.add(modelClass)//In your arraylist save the data
}
} catch (JSONException e) {
e.printStackTrace();
}
}
First of all you need to check what type response you getting from server i.e (JsonObject or JsonArray).
public void jsonParse() {
String url = "http://178.128.166.68/getUserInfo.php";
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
/*
if its JSONObject
*/
JSONObject jsonobject = new JSONObject(response);
String value= jsonobject.getString("value");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("phone", phone);
params.put("password", password);
return params;
}
};
mQueue.add(request);
}
as per your question ... you want to store response in jsonObject but in code you are store response in jsonArray
parentObject = new JSONArray(response);
so you must have to confirm response is in object or array.
if response is in object (like {}) change to parentObject = new JSONObject(response);
else change type of parentObject to JSONArray

How can I pass a simple Integer[] to Volley?

I am using Volley successfully to pass and receive JSONArrays and JSONObjects, but the API I'm using requires that I pass in a simple Integer array [1,2,3] in a PUT request. Any ideas?
Here is a snippet from the API documentation.
PUT api/commuters/{id}/favorites
Update the list of favorite commuters associated with the specified
commuter.
REQUEST
Body Parameters: Collection of integer Request Formats
application/json, text/json, text/html Sample: [ 1, 2 ]
RESPONSE
none
The trick to sending text to a Volley Request is overriding the getBoddy method to print out your text/json.
Here is my method for putting the integer array:
public static void putFavorites(final JSONArray data, final MyApp.StringCallback callback) {
String url = APP_API + "commuters/" +
MyApp.getPrefs().getInt("commuterId", 0) + "/favorites";
StringRequest stringRequst = new StringRequest(Request.Method.PUT, url,
new Response.Listener<String>() {
#Override
public void onResponse(String result) {
try {
callback.onSuccess(result);
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
callback.onError(volleyError);
}
}) {
#Override
public String getBodyContentType() {
return "text/json";
}
#Override
public byte[] getBody() throws AuthFailureError {
Log.d(TAG, (data.toString()).getBytes().toString());
return (data.toString()).getBytes();
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers = VolleySingleton.getInstance(GACommuter.getAppContext()).getVolleyHeader("text/json");
return headers;
}
};
stringRequst.setRetryPolicy(new DefaultRetryPolicy(
20000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
));
addToRequestQueue(stringRequst);
}

How To Convert HttpURLConnection to Volley

I have google a lot but i can find solution about my issue my old code for call web service from my activity i have pass two parameter one is link means URL and second is parameters is for data i have to send to server.
problem is i have to use volley in place of following code
call retrieveStream("www.xyz.com/abc.php","data=dfsds");
public static String retrieveStream(String link, String parameters) {
try {
link = link.replace(" ", "%20");
URL url = new URL(link);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
OutputStreamWriter request = new OutputStreamWriter(
connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(
connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
// Response from server after login process will be stored in
// response variable.
String response = sb.toString();
// You can perform UI operations here
isr.close();
reader.close();
return response;
} catch (IOException ignored) {
ignored.printStackTrace();
}
return "";
}`
I have implement in volley
StringRequest sr = new StringRequest(Request.Method.POST,
JSONUtils.WEB_SERVICE + "pausetest.php",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// mPostCommentResponse.requestCompleted();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// mPostCommentResponse.requestEndedWithError(error);
Toast.makeText(getActivity().getApplicationContext(),
error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("allanswer", alldata);
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;
}
};
AppController.getInstance().addToRequestQueue(sr);`
FYI. This is assuming that your using application/x-www-form-urlencoded, as to a multi-part-form. I believe the Volley document/videos state somewhere that it is not meant for large data transfers.
I usually make a separate class for my various distinct Volley call, especially for restful processing or reuse as follows:
package com.your.package;
public class MyVolleyRequest1 {
public void myUniqueVolleyRequest(final String _parameter1, final String _parameter2) {
if (!isNetworkAvailable()) {
apiNetworkUnAvailableMsg("No network for this function.");
return;
}
RequestQueue queue = MyVolley.getRequestQueue();
StringRetroFIXRequest myReq = new StringRetroFIXRequest(Method.POST,
getMyContext().getString(R.string.http_url),
createMyReqSuccessListener(),
createMyReqErrorListener()) {
public Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("parameter 1", _parameter1);
params.put("parameter 2", _parameter2);
return params;
}
;
};
queue.add(myReq);
}
private Response.Listener<String> createMyReqSuccessListener() {
return new Response.Listener<String>() {
#Override
public void onResponse(String response) {
setResponseSuccess(response);
}
};
}
private Response.ErrorListener createMyReqErrorListener() {
return new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
setResponseSuccess(error.toString());
}
};
}
private void setResponseSuccess(String result) {
EventBus.getDefault().post(new EventBusResultsClassResponseDone(result));
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getMyContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private void apiNetworkUnAvailableMsg(String _purpose) {
String mReturn = "Internet connection unavailable. Try " + _purpose + " at a later time.";
EventBus.getDefault().post(new VolleyReturnEvent(mReturn));
}
}
I also use EventBus, so that I can loosely couple the return value(s), especially, if I decide I want to put those results into a model (pojo), like for using MVC/MVP type processing or say specialized processing of json, etc.
Optionally I also like to use OKHttp in combination Volley, here are the dependencies for gradle in Android Studio.
compile 'de.greenrobot:eventbus:2.1.0'
compile 'com.squareup.okio:okio:1.1.0'
compile 'com.squareup.okhttp:okhttp:2.2.0'
If you are just going to do restful processing Retrofit is a cool library.
Implementing in your Activity or Fragment you then define the above class and instantiate with the parameters, if needed. My example has 2 parameters. Then you implement EventBus, define the eventbus class, and include the return events via EventBus in your app, including the generic VolleyError which is returned as a separate event for error processing.
Here's a gist of what I'd put in my activity to call and then get responses from Volley/OKHttp.
#Override
protected void onResume() {
super.onResume();
EventBus.getDefault().register(this);
requestMyVolleyResponse1();
}
#Override
protected void onPause() {
EventBus.getDefault().unregister(this);
super.onPause();
}
private void requestMyVolleyResponse1() {
MyVolleyRequest1 mVolleyRequest1 = new MyVolleyRequest1();
mVolleyRequest1.MyVolleyRequest1("Parameter 1 value","Parameter 2 value");
}
public void onEventMainThread(MyVolleyRequest1Done event) {
// Your successful response processing.
}
public void onEventMainThread(VolleyReturnEvent event) {
// Your Error Processing
;
}
The EventBus return classes that you have to define (VolleyReturnEvent, MyVolleyRequest1Done) are really simple, i.e.
public class VolleyReturnEvent {
public final String message;
public VolleyReturnEvent(String message) {
this.message = message;
}
}

Categories