I want to use from open street map API
when i send request to Reverse Geo coding Api with volley
This error is displayed
com.android.volley.authfailureerror
But this API don't need to any token
this is my Code:
String url = "https://nominatim.openstreetmap.org/reverse?format=json&lat="+lat+"&lon="+lng;
Response.Listener<JSONObject> listener = new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
try
{
JSONObject address = response.getJSONObject("address");
final String city = address.getString("town");
final String county = address.getString("county");
selectcity = true;
String temp = county.substring(county.indexOf(" "),county.length());
ed.putString("lat", lat+"");
ed.putString("lng", lng+"");
ed.putString("location", temp);
ed.apply();
progressDialog.dismiss();
RequestQueue mRequestQueue;
mRequestQueue =AppController.getInstance().getRequestQueue();
mRequestQueue.cancelAll("AppController");
locationManager.removeUpdates(LocationActivity.this);
}
catch (JSONException e)
{
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Erorr", Toast.LENGTH_LONG).show();
RequestQueue mRequestQueue;
mRequestQueue =AppController.getInstance().getRequestQueue();
mRequestQueue.cancelAll("AppController");
progressDialog.dismiss();
locationManager.removeUpdates(LocationActivity.this);
}
}
};
Response.ErrorListener errorListener = new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
RequestQueue mRequestQueue;
mRequestQueue =AppController.getInstance().getRequestQueue();
mRequestQueue.cancelAll("AppController");
progressDialog.dismiss();
locationManager.removeUpdates(LocationActivity.this);
}
};
final JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, listener, errorListener){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
headers.put("accept-language", "fa");
return headers;
}
};
request.setTag("AppController");
AppController.getInstance().addToRequestQueue(request);
In addition when I use from this URL in postman It works correctly
try this way
RequestQueue requestQueue = Volley.newRequestQueue(mContext);
StringRequest stringRequest = new StringRequest(Request.Method.GET, Your_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("===","onErrorResponse "+error)
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
Log.d("===","AuthFailureError");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
return params;
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
try {
} catch (Exception e) {
}
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
stringRequest.setRetryPolicy(new RetryPolicy() {
#Override
public int getCurrentTimeout() {
return 50000;
}
#Override
public int getCurrentRetryCount() {
return 50000;
}
#Override
public void retry(VolleyError error) throws VolleyError {
}
});
requestQueue.add(stringRequest);
Related
I want to change my StringRequest to a JsonArrayRequest in order to separate the return into different variables.
As I run this code below:
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("res", response);
if (response.equals("failure")) {
Toast.makeText(MainActivity.this, "Ungültige Anmeldedaten", Toast.LENGTH_SHORT).show();
} else {
TV.setText(response);
//ID = Integer.parseInt(response);
//switchToMain();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString().trim(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> data = new HashMap<>();
data.put("email", email);
data.put("password", password);
return data;
}
};
requestQueue.add(stringRequest);
I return the response:
[{"id":"6","Username":"a","Email":"a","Password":"0cc175b9c0f1b6a831c399e269772661","Status":"Online"}]
, which is a JsonArray, isn´t it?
When I try to make a JsonArrayRequest I receive errors:
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonArrayRequest queue = new JsonArrayRequest(Request.Method.POST,URL,null,new Response.Listener<JSONArray>(){
#Override
public void onResponse(JSONArray response) {
if (response.equals("null")) {
Toast.makeText(MainActivity.this, "Ungültige Anmeldedaten", Toast.LENGTH_SHORT).show();
} else {
//ID = Integer.parseInt(response);
//switchToMain();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString().trim(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> data = new HashMap<>();
data.put("email", email);
data.put("password", password);
return data;
}
};
requestQueue.add(queue);
I receive the following error:
com.android.volley.ParseError: org.json.JSONException: End of input at character 0 of
Where is my mistake?
My API working correctly but when i send data using android app its not inserting data.
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { JSONObject jsonBody = new JSONObject();
try {
`jsonBody.put("ID", "Android Volley Demo");
jsonBody.put("Name", "BNK");
final String requestBody = jsonBody.toString();
StringRequest stringRequest=new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
That is my API.Its working correctly.
public HttpResponseMessage Post([FromBody]Login log)
{
db.Logins.Add(log);
db.SaveChanges();
var message = Request.CreateResponse(HttpStatusCode.Created, log);
message.Headers.Location = new Uri(Request.RequestUri + log.ID.ToString());
return message;
}
This is my Code i am Posting data but not inserting in SQL Server but when i test API by sending raw data its working correctly.
Try this:
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String ServerResponse) {
Log.i("VOLLEY Response : ", ServerResponse);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("VOLLEY ErrorResponse : ", volleyError.toString());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("Name", "BNK");
return params;
}
};
// Creating RequestQueue.
RequestQueue requestQueue = Volley.newRequestQueue(context);
// Adding the StringRequest object into requestQueue.
requestQueue.add(stringRequest);
Check this one
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://...";
JSONObject jsonBody = new JSONObject();
jsonBody.put("firstkey", "firstvalue");
jsonBody.put("secondkey", "secondobject");
final String mRequestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("LOG_VOLLEY", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("LOG_VOLLEY", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
My android application uses multiple network calls in a single activity and i have several of these activities where i have to use both post and get requests. I want to create a single "VolleyWebservice" class and call the same in multiple activities instead of writing the complete volley code. I am relatively new to android development and i don't understand where i am going wrong.
public class VolleyWebService {
public JSONObject result;
public JSONObject getResponse(String url, Context mContext) {
RequestQueue mQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Anshuman" + response.toString());
result = response;
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
mQueue.add(request);
return result;
}
}
The method in My activity where i am calling this class
private void callFunctionGetDist() {
ProgressDialog progressDialog;
progressDialog = ProgressDialog.show(recorddata.this, "", "Please Wait...", true);
JSONObject response = new VolleyWebService().getResponse(urlConfigClass.GET_DISTRICT, this);
try {
if(response.toString().contains("Status:Success,Details")){
arrDistName.clear();
arrDistCode.clear();
arrDistName.add("Select District Name");
arrDistCode.add("Select District Code");
JSONArray jsonArray = response.getJSONArray("Status:Success,Details");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jobJ = jsonArray.getJSONObject(i);
String scheName = jobJ.getString("post");
JSONObject jobJDist = new JSONObject(scheName);
String distname = jobJDist.getString("District");
String distcode = jobJDist.getString("DistrictCode");
arrDistName.add(distname);
arrDistCode.add(distcode);
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<>(recorddata.this,
R.layout.custom_textview_to_spinner, arrDistName);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
district.setAdapter(dataAdapter);
progressDialog.dismiss();
}else{
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Response is null or empty", Toast.LENGTH_LONG).show();
}
} catch (Exception volleyError) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), volleyError.getMessage(), Toast.LENGTH_LONG).show();
}
}
I tried creating the same class but i am not able to get the response to other activities. Although i am getting the correct response in the Volley jsonbject response, the response return null in other activities.
I want to have the result object return the response in my recorddata activity
This is what i have tried so far, no luck though!
public void postResponse (String url, Context mContext, final VolleyResponseListener listener) {
try {
String encodedUrl = url.replace(" ", "%20") + "";
if (encodedUrl.contains("("))
encodedUrl = encodedUrl.replace("(", "%28");
if (encodedUrl.contains(")"))
encodedUrl = encodedUrl.replace(")", "%29");
encodedUrl = encodedUrl.replace(" ", "%20");
RequestQueue mQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POst, encodedUrl, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Anshuman" + response.toString());
listener.onSuccess(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
listener.onError(error);
}
}) {
#Override
protected Map<String, String> getParams() {
return new HashMap<>();
}
};
mQueue.add(request);
} catch (Exception e) {
e.printStackTrace();
}
}
For the sake of achieving your goal, (without taking in to consideration architecture and coding principles), you can pass a callback:
public class VolleyWebService {
public interface VolleyResponseListener {
void onSuccess(JSONObject response);
void onError(VolleyError error);
}
public JSONObject result;
public JSONObject getResponse(String url, Context mContext, VolleyResponseListener listener) {
RequestQueue mQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Anshuman" + response.toString());
listener.onSuccess(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
listener.onError(error);
}
});
mQueue.add(request);
return result;
}
}
To use it:
volleyWebService.getResponse("your url", context, new VolleyResponseListener() {
#Override
void onSuccess(JSONObject response) {
//do what you want on success
}
#Override
void onError(VolleyError error) {
//do what you want on error
}
});
I am using simmilar fucntion for creating GET and POST api requests, but the GET function set textview to response body and I dont know how to read the status code and the POST function set textview to the response code and I dont know how to read response body. Can you help me, please?
I also tried to log in parseNetworkResponse() response.data.toString() but thats is not the data that api returns. Maybe I need to encode it somehow?
public void createGet(Context context, String url) {
final TextView apiResultTextview = (TextView) ((Activity)
context).findViewById(R.id.api_result_textview);
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(context);
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
apiResultTextview.setText("Response is: " + response.substring(0, 50));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
apiResultTextview.setText(error.toString());
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
public void createPost(Context context, String url, JSONObject body) {
final TextView apiResultTextview = (TextView) ((Activity) context).findViewById(R.id.api_result_textview);
RequestQueue requestQueue = Volley.newRequestQueue(context);
final String mRequestBody = body.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("LOG_RESPONSE", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("LOG_RESPONSE", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
apiResultTextview.setText("Response is: " + responseString);
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
}
I solved it by changing method for call to code below. Problem was probably in JsonObjectRequest vs StringRequest. That's why I was getting only response code string.
public void createCall(int type, String url, JSONObject data, final int callback) {
JsonObjectRequest jsonRequest = new JsonObjectRequest(type, url,data,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Response", response.toString());
try {
callback(response, callback);
} catch (Exception e){
Log.d("API callback error", e.getMessage());
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error response", error.toString());
}
}
);
queue.add(jsonRequest);
}
add this code in you onResponse() Method
JSONObject jsonObj = new JSONObject(response);
String response_value = jsonObj.getString("response");
How do I return serverAnswer behind onResponse?
Because in onResponse, serverAnswer gets data, but behind onResponse it's an empty variable...
For example, if I try to show a Toast with serverAnswer in onResponse, it's alright, serverAnswer has data from JSON string. But if try to show a Toast with serverAnswer behind onResponse - I get an empty Toast.
And addUser returns an empty String too.
public String addUser(final String username, final String email, final String password, final Context context) {
StringRequest request = new StringRequest(
Request.Method.POST,
REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(final String response) {
try {
JSONObject jsonObject = new JSONObject(response);
final JSONObject status = jsonObject.getJSONObject("Result");
serverAnswer = status.getString("Server answer");
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
serverAnswer = error.getMessage();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put(KEY_USERNAME, username);
params.put(KEY_EMAIL, email);
params.put(KEY_PASSWORD, password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(request);
return serverAnswer;
}