I feel like this is a very basic concept missunderstanding. In my Android app I make HTTP requests using Volley lib. At first I made the requests through a JsonObjectRequest in the Activity code and worked right, but now I separated the request code in a class apart so I can call it from any Activity. The new class has a method that returns the requested JSONObject but any "json action" I do over the returned object ends in an error.
Here is the new class code, JSONRequests:
public class JSONRequests {
private JSONObject mResponse;
private String mURL = "https://myurl.com/";
public JSONObject getJSONObject(final String credentials, final String path) {
final JsonObjectRequest mRequest = new JsonObjectRequest(mURL.concat(path), null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
mResponse = response;
try {
Log.d("RESPONSE", mResponse.getString("id")); // It works here
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", "Basic " + credentials);
return headers;
}
};
MyApplication.getInstance().getRequestQueue().add(mRequest);
return mResponse;
}
}
And here is how I call getJSONObject from MyActivity:
JSONRequests mRequest = new JSONRequests();
JSONObject mInfo = mRequest.getJSONObject(mEncodedCredentials, mPath);
try {
Log.d("RESPONSE", mInfo.getString("id")); // This doesn't work
} catch (JSONException e) {
e.printStackTrace();
}
When in the Activity file, I used "response" as a JSONObject and it worked, but now separated it won't. I don't know if is a error with JSONObject or just that I'm not getting the returned object in the correct way. Thanks in advance.
Related
I want to send a DELETE request to an API to delete a city with the given id. In the API request documentation it says that the DELETE request requires as parameters the authentication token and the city id. When I run the code below I always get a com.android.volley.AuthFailureError.
Here's my code:
void deleteCity(String cityId, final VolleyResponseListener volleyResponseListener){
String url = baseUrl + "city";
try {
JSONObject params = new JSONObject();
params.put("token", token);
params.put("city_id", cityId);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.DELETE, url, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try{
String success = response.get("success").toString();
if(success.equals("true")){
volleyResponseListener.onResponse();
}else{
String errorMessage = response.get("errorMessage").toString();
throw new Exception(errorMessage);
}
} catch (Exception e) {
volleyResponseListener.onError(e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error);
volleyResponseListener.onError("Volley Error");
}
});
requestQueue.add(jsonObjectRequest);
}catch (JSONException e){
volleyResponseListener.onError("Param error");
}
}
UPDATE:
I solved the problem by adding the city id as a query in the HTTP request and sent the authentication token in the header. Here is the final code:
void deleteCity(String cityId, final VolleyResponseListener volleyResponseListener){
String url = baseUrl + "city?city_id="+cityId;
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.DELETE, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try{
String success = response.get("success").toString();
if(success.equals("true")){
volleyResponseListener.onResponse();
}else{
String errorMessage = response.get("errorMessage").toString();
throw new Exception(errorMessage);
}
} catch (Exception e) {
volleyResponseListener.onError(e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error);
volleyResponseListener.onError("Volley Error");
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null || headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
headers.put("token", token);
return headers;
}
};
requestQueue.add(jsonObjectRequest);
}
I want to send Array to server that looks like this :
"Array":["name"="something", "description"="something"]
To perform request i'm using this method :
private void saveNote(final int id, final String name, final String des, final String assing) {
Log.d(TAG, "Saving");
StringRequest stringRequest = new StringRequest(Request.Method.POST, Api.URL_CREATE_NOTE,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response", response.toString());
try {
JSONObject obj = new JSONObject(response);
if (!obj.getBoolean("error")) {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> postParams = new HashMap<>();
Map<String, String> tableData= new HashMap<>();
tableDataParam.put("name",name);
tableDataParam.put("description",des);
postParams.put("Array[]", tableDataParam.toString());
return params;
}
};
VolleySingletonNotes.getInstance(context).addToRequestQueue(stringRequest);
}
First issue is that i can pass only String in postParams HashMap, so when i do tableData.toString the tableData have string brackets like this:
"Array":["{name=something, desciption=something}"]
And the second issue is that tableData HashMap for some reason dont put his String parameters in string brackets as you can see in example below first issue.
I already tried make JsonArray that fix the second issue but the first issue still remains, plus it automatically create backslashes(they dont show when i type them here)
Can anyone help me with this issue? Thanks.
I want to update the "Pass" field using WebAPI, I have created an HTTP PUT Request using Asp.Net WEB API and Android Java with Volley.
through Postman it's updating field value but when I test through my App it's updating the blank value in DB.
Thanks in advance.
private void callPUTDataMethod(String name, String job) {
loadingPB.setVisibility(View.VISIBLE);
String url = URL;
RequestQueue queue = Volley.newRequestQueue(PassUpdt.this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.PUT, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
loadingPB.setVisibility(View.GONE);
jobEdt.setText("");
userNameEdt.setText("");
// on below line we are displaying a toast message as data updated.
Toast.makeText(PassUpdt.this, "Data Updated..", Toast.LENGTH_SHORT).show();
try {
JSONObject jsonObject = new JSONObject("Pass");
String output = "Password Updated";
responseTV.setText(output);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(PassUpdt.this, "Fail to update data..", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("EmpCd", "P010");
params.put("Pass", "12345");
params.put("Content-Type", "application/json; charset=utf-8");
return params;
}
};
queue.add(jsonObjectRequest);
}
}
I need to use Mediaplayer inside a JsonObjectRequest. My Code is like this
obreq = new JsonObjectRequest(Request.Method.GET, url,
// The third parameter Listener overrides the method onResponse() and passes
//JSONObject as a parameter
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
MediaPlayer mediaPlayer = MediaPlayer.create(this,R.raw.ok);
mediaPlayer.start();
JSONObject obj = response.getJSONObject("result");
}
// Try and catch are included to handle any errors due to JSON
catch (JSONException e) {
// If an error occurs, this prints the error to the log
Log.e("Errore: ", e.getLocalizedMessage());
e.printStackTrace();
}
}
},
// The final parameter overrides the method onErrorResponse() and passes VolleyError
//as a parameter
new Response.ErrorListener() {
#Override
// Handles errors that occur due to Volley
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
MediaPlayer mediaPlayer = MediaPlayer.create(this,R.raw.error);
mediaPlayer.start();
throw new NullPointerException("uuuuuu");
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> customHeaders = new HashMap<>();
String login_url = Helper.getConfigValue(getApplicationContext(), "login_url");
String pwd_url = Helper.getConfigValue(getApplicationContext(), "pwd_url");
String credentials = login_url + ":" + pwd_url;
String auth = "Basic "
+ Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
customHeaders.put("Content-Type", "application/json; charset=utf-8");
customHeaders.put("Authorization", auth);
return customHeaders;
}
};
shareedit delete flag
but i get the error
"Cannot resolve method 'create(anonymous
com.android.volley.Response.Listener, int)"
in MediaPlayer line
How can I solve the problem?
Thanks
As your "this" is referring to you volley object
MediaPlayer.create(this,R.raw.ok);
replace it with you activity reference, like
MediaPlayer.create(yourActivity.this,R.raw.ok);
I would like to send and receive a Json Array with volley.
Now I can receive an array and it's ok but I don't know how to send a request (For example: with post method).
JsonArrayRequest arrayReq = new JsonArrayRequest(URL,
new Listener<JSONArray>() {
}
List<Map<String,String>> listMap = new ArrayList<Map<String, String>>();
Map<String,String> map = new HashMap<String,String>();
try {
map.put("email", customer.getEmail());
map.put("password",customer.getPassword());
} catch (Exception e) {
e.printStackTrace();
}
listMap.add(map);
String url = PersonalConstants.BASE_URL+"/url";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.POST, url, String.valueOf(new JSONArray(listMap)),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Log.d(App.TAG, jsonObject.toString());
}
}, new Response.ErrorListener (){
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d(App.TAG,volleyError.toString());
}
}
);
App.getInstance().getmRequestQueue().add(jsonObjectRequest);
Here is an example:
// Define the web service URL
final String URL = "http://www.someurl.com";
// POST params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("name", "raha tamjid");
// Define the POST request
JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
// Add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);
How the POST request differs is that it takes a JSONObject as parameter.
EDIT 1:
If you have Volley installed as a library project in your IDE, then just define a new constructor
public JsonArrayRequest(int method, String url, JSONObject jsonRequest,
Listener<JSONArray> listener, ErrorListener errorListener) {
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener, errorListener);
}
inside the class JsonArrayRequest which is present in the Volley library code. Now you can use this to create JsonArrayRequest objects and add them to the RequestQueue.
EDIT 2:
1. Get the Volley library project from here. Download the project and set it up in your IDE.
2. Make the modification to the JsonRequest class (found in com.android.volley.toolbox namespace) as discussed in EDIT 1.
3. Delete the volley.jar from the libs folder of your APPLICATION PROJECT.
4. Now go to Project Properties -> Android -> Library and click on Add. From here select the Volley project. Clean & Rebuild.
5. Now in your APPLICATION PROJECT you can make a POST JsonArrayRequest just like how we make a POST JsonObjectRequest and get a JSONArray in the Response.
Create a class and extend JsonArrayRequest then override
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("name", "value");
return params;
}
and add a new constructor and in it call
super(Method.POST, url, null, listener, errorListener);
or use this class
public class PostJsonArrayRequest extends JsonRequest<JSONArray> {
/**
* Creates a new request.
* #param url URL to fetch the JSON from
* #param listener Listener to receive the JSON response
* #param errorListener Error listener, or null to ignore errors.
*/
public PostJsonArrayRequest(String url, Response.Listener<JSONArray> listener, Response.ErrorListener errorListener) {
super(Method.POST, url, null, listener, errorListener);
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("name", "value");
return params;
}
#Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString =
new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONArray(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
}
Create a new java class named JsonArrayPostRequest now you can use it like the previous request, just replace JSONArrayRequest with JsonArrayPostRequest and pass the correct parameters
public class JsonArrayPostRequest extends Request<JSONArray>{
private Map<String,String> mParam;
private Listener<JSONArray> mListener;
public JsonArrayPostRequest(String url,Listener<JSONArray> listener, ErrorListener errorListener,Map param) {
super(Request.Method.POST, url, errorListener);
mListener=listener;
mParam=param;
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return mParam;
}
#Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString =
new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONArray(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
#Override
protected void deliverResponse(JSONArray response) {
mListener.onResponse(response);
}
}
USE:
JsonArrayPostRequest request = new JsonArrayPostRequest(URL,new Response.Listener<JSONArray>(),
new Response.ErrorListener() ,params);