I am using a Web API to be integrated into my app. I a using .net server APIs for the same but the problem is that when I am passing parameters with URL then it throws an error if any parameter of API contains space. As I am passing string values but it throws me error just because of space and if I remove space then everything is perfect. Please help!!!
private void getEnterLoadDetail() {
pBar.setVisibility(View.VISIBLE);
pref = getContext().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
String userName = pref.getString(KEY_USER_NAME, "username");
Log.e("TAG", "USERNAME" + userName);
tripId = txtTripId.getText().toString();
materialCode = txtMaterialCode.getText().toString();
vendorCode = txtVendorCode.getText().toString();
String url = "http://18.216.239.216:8086/api/Mobile?username="+userName+"&tripid=" + tripId + "&VehicleNo=" + vehicleNo + "&MaterialName=" + materialname + "&MaterialCode=" + materialCode + "&VendorName=" + vendorName + "&VendorCode=" + vendorCode + "&MaterialRate=" + rate + "&Remarks="+remarks+"";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("response", response.toString());
try {
if (response.contains("success")) {
Toast.makeText(getActivity(), R.string.load_detail_submitted, Toast.LENGTH_LONG).show();
edtVehicleNo.setText("");
edtRate.setText("");
edtRemarks.setText("");
txtMaterialCode.setText("Material Code");
txtVendorCode.setText("Vendor Code");
spinnerVendorName.setSelection(0);
spinnerMaterialName.setSelection(0);
txtTripId.setText("Trip Id");
}
} catch (Exception e) {
e.printStackTrace();
Activity activity = getActivity();
if (activity != null && isAdded()) {
Toast.makeText(activity, R.string.some_error_occured, Toast.LENGTH_LONG).show();
}
}
pBar.setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: " + error.getMessage());
Activity activity = getActivity();
if (activity != null && isAdded()) {
Toast.makeText(activity, R.string.some_error_occured, Toast.LENGTH_LONG).show();
pBar.setVisibility(View.GONE);
}
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
//adding the string request to request queue
requestQueue.add(stringRequest);
}
-------- materialname and all other variables contains spaces and API throws error.
Try
String url = "http://18.216.239.216:8086/api/Mobile?username="+userName+"&tripid=" + tripId + "&VehicleNo=" + vehicleNo + "&MaterialName=" + materialname + "&MaterialCode=" + materialCode + "&VendorName=" + vendorName + "&VendorCode=" + vendorCode + "&MaterialRate=" + rate + "&Remarks="+remarks+"";
String convertedUrl = URLEncoder.encode(url, "utf-8");
Related
The response format is {"status":"201","message":"OTP is created and sent."}, I need to get the status & message values, but String name = response.getString("name"); is showing red line error.
Here is my code:
public void sendData() {
final JSONObject json = new JSONObject();
final TextView serverResp = findViewById(R.id.connectionStatus);
try {
json.put("mobile", "12312312");
} catch (JSONException e) {
e.printStackTrace();
}
String url = getResources().getString(R.string.url_login);
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, json,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(REQ_TAG, response.toString());
String name = response.getString("name");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
serverResp.setText("Error getting response\n" + error.toString());
Log.d(REQ_TAG, "Error: " + error.toString()
+ "\nStatus Code " + error.networkResponse.statusCode
+ "\nResponse Data " + error.networkResponse.data
+ "\nCause " + error.getCause()
+ "\nmessage" + error.getMessage());
}
});
jsonObjectRequest.setTag(REQ_TAG);
requestQueue.add(jsonObjectRequest);
// do i need the following line?
//RequestQueueSingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
}
Becuase there is no key name in JSON response
try this
String status= response.getString("status");
String message= response.getString("message");
I have two Android apps that communicate with a Web server using Volley calls: one app waits for the other to post a short message. Most of the time this works fine: the waiting app gets the response from the posting app. However, every 5 or so times, the response is sent by the first app but the second one never gets a response. Here is the relevant code:
Posting code:
private synchronized void setGameProgress(String user_id, int pos, String letter, String accessToken) {
String url = "";
RequestQueue queue = Volley.newRequestQueue(activity);
try {
activity.runOnUiThread(new Runnable() {
public void run() {
spinner.setVisibility(View.VISIBLE);
}
});
url = "https://www.chiaramail.com:443/GameServer/GameServer?user_ID=" + URLEncoder.encode(user_id, "UTF-8") + "&token=" + URLEncoder.encode(accessToken, "UTF-8") + "&cmd=" + URLEncoder.encode("SETGAME PROGRESS ", "UTF-8") + "&parms=" + URLEncoder.encode(user_id + " " + pos + " " + letter, "UTF-8");
} catch (UnsupportedEncodingException e) {
Toast.makeText(activity, getString(R.string.error_updating_progress) + e.getMessage(), Toast.LENGTH_LONG).show();
spinner.setVisibility(View.INVISIBLE);
}
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (!response.startsWith("42 ")) {
queue_builder.setMessage(getString(R.string.error_updating_progress) + " " + response);
queue_alert = queue_builder.create();
queue_alert.show();
}
spinner.setVisibility(View.INVISIBLE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
volleyError = error;
Toast.makeText(activity, getString(R.string.error_updating_progress) + volleyError.getMessage(), Toast.LENGTH_LONG).show();
spinner.setVisibility(View.INVISIBLE);
}
});
queue.add(stringRequest);
}
Wait code:
private synchronized void getGameProgress(final String user_id, final String accessToken) {
String url = "";
RequestQueue queue = Volley.newRequestQueue(activity);
try {
url = "https://www.chiaramail.com:443/GameServer/GameServer?user_ID=" + URLEncoder.encode(user_id, "UTF-8") + "&token=" + URLEncoder.encode(accessToken, "UTF-8") + "&cmd=" + URLEncoder.encode("GETGAME PROGRESS ", "UTF-8") + "&parms=" + URLEncoder.encode(user_id, "UTF-8");
} catch (UnsupportedEncodingException e) {
Toast.makeText(activity, getString(R.string.error_getting_progress) + e.getMessage(), Toast.LENGTH_LONG).show();
}
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.startsWith("43 ")) {
StringTokenizer st = new StringTokenizer(response.substring(3));
String position = st.nextToken();
String letter = st.nextToken();
updateTheirProgress(Integer.valueOf(position), letter);
getGameProgress(opponent_ID, AccessToken.getCurrentAccessToken().getToken());
} else {
queue_builder.setMessage(getString(R.string.error_getting_progress) + " " + response);
queue_alert = queue_builder.create();
queue_alert.show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
volleyError = error;
Toast.makeText(activity, getString(R.string.error_getting_progress) + volleyError.getMessage(), Toast.LENGTH_LONG).show();
}
});
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
60000, 5,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(stringRequest);
}
I know that the server is processing the requests from the server log:
10212211883390475 2017-11-26, 17:57:40 42
10212211883390475 2017-11-26, 17:57:40 43 4 s
I've spent several days on this and other than a Volley bug, I can't see what the problem is. Any thoughts?
The problem was due to the Apache server timing out after five minutes. The problem was resolved when I changed the timeout setting in Apache to -1 (infinite timeout).
/**
* Method to make json array request where response starts with [
* Requesting data from url
* */
private String urlJsonArry_local = "http://www.endorecord.in/endorecord/hospitaladmin/Api/device_hospitals.php?deviceid=";
private void makeJsonArrayRequest() {
showpDialog();
JsonArrayRequest req = new JsonArrayRequest(urlJsonArry_local +androidID,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
String name = person.getString("hospitalid");
String email = person.getString("hospital_name");
/*JSONObject phone = person
.getJSONObject("phone");
String home = phone.getString("home");
String mobile = phone.getString("mobile");
*/
jsonResponse += "Name: " + name + "\n\n";
jsonResponse += "Email: " + email + "\n\n";
//jsonResponse += "Home: " + home + "\n\n";
//jsonResponse += "Mobile: " + mobile + "\n\n\n";
}
Toast.makeText(getApplicationContext(), jsonResponse, Toast.LENGTH_LONG).show();
//txtResponse.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
you should be passing your url in the request "http://www.google.com"+androidID not this. And the Url urlJsonArry_local that you have mentioned above returns json object response not jsonArray, Your code and Json reponse are completely irrelavant
for the Json respone in above url
private String urlJsonArry_local = "http://www.endorecord.in/endorecord/hospitaladmin/Api/device_hospitals.php?deviceid=";
RequestQueue queue = MyVolley.getRequestQueue();
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,urlJsonArry_local,null/* paramateres passed here*/,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONObject jObject = response;
String status = jObject.getString("status");
JSONArray hospitalArray = jObject.getJSONArray("hospital");
//your for loop to parse hospital array here
hideProgressDialog();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideProgressDialog();
}
});
queue.add(jsObjRequest);
I am making multiple Volley StringRequests.
The requestfriendlist method fetches a list of profiles related to "Naruto". The requestimagelink method fetches Images for each profile it got in the previous method result.However the reponse (imagelink) I am getting is not in order from the requestimagelink method is not in order.
For Example -
Request[1,2,3,4]
Response[2,1,4,3] or any other order.
Please help me fix this issue.
Attaching Code Snippet
protected void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomImageAdapter(this, imageList);
listView.setAdapter(adapter);
requestfriendlist("Naruto");
}
private void requestfriendlist (String profilename)
{
String uri = String.format(Config.URL_REQUEST_FRIENDS + "?current_user=%1$s", profilename);
Log.d(TAG + "uri", uri);
StringRequest strReq = new StringRequest(
Request.Method.GET,
uri,
new Response.Listener<String>()
{
#Override
public void onResponse (String response)
{
try
{
JSONObject responseObj = new JSONObject(response);
Log.d(TAG + "friends", response);
JSONArray jResult = responseObj.getJSONArray("req_users");
Toast.makeText(MainActivity.this, jResult.toString(), Toast.LENGTH_SHORT).show();
for(int i = 0; i < jResult.length(); i++)
{
JSONObject jresponse = jResult.getJSONObject(i);
String profile = jresponse.getString("userid");
friendlist.add(profile);
}
for(int i = 0; i < friendlist.size(); i++)
requestimagelink(friendlist.get(i));
}
catch(JSONException e)
{
Log.d(TAG, "error" + e.getMessage());
Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse (VolleyError error)
{
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}
);
MyApplication.getInstance().addToRequestQueue(strReq);
}
private void requestimagelink (final String profilename)
{
String uri = String.format(Config.URL_REQUEST_IMAGE + "?userid=%1$s", profilename);
Toast.makeText(MainActivity.this, uri, Toast.LENGTH_SHORT).show();
Log.d(TAG, "uri" + uri);
StringRequest strReq = new StringRequest(
Request.Method.GET,
uri,
new Response.Listener<String>()
{
//response from the server
#Override
public void onResponse (String response)
{
try
{
JSONObject responseObj = new JSONObject(response);
((TextView) findViewById(R.id.tvprofilejson)).setText(response);
Log.d(TAG, response);
JSONArray jResult = responseObj.getJSONArray("photos");
for(int i = 0; i < jResult.length(); i++)
{
JSONObject jresponse = jResult.getJSONObject(i);
ImageClass img = new ImageClass();
img.setThumbnailUrl(jresponse.getString("name"));
img.setTitle(profilename);
imageList.add(img);
//imagelinks.add(jresponse.getString("name"));
adapter.notifyDataSetChanged();
}
}
catch(JSONException e)
{
Log.d(TAG, "error" + e.getMessage());
Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse (VolleyError error)
{
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}
);
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(strReq);
}
Here is how to link your profiles to their images using a hashMap:
ArrayList<String> friendlist = new ArrayList<String>();
/**
Keeps the profiles' images. Later in your arrayAdapter, where you want show thumbnail image, you must
get corresponding ImageClass from of profile with profileName. If the result is null means that the image
is not loaded yet, otherwise you can use the ImageClass object to retreive profile's image.
*/
HashMap<String, ImageClass> profile_img_Hash = new HashMap<String, ImageClass>();
protected void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomImageAdapter(this, imageList);
listView.setAdapter(adapter);
requestfriendlist("Naruto");
}
private void requestfriendlist (String profilename)
{
String uri = String.format(Config.URL_REQUEST_FRIENDS + "?current_user=%1$s", profilename);
Log.d(TAG + "uri", uri);
StringRequest strReq = new StringRequest(
Request.Method.GET,
uri,
new Response.Listener<String>()
{
#Override
public void onResponse (String response)
{
try
{
JSONObject responseObj = new JSONObject(response);
Log.d(TAG + "friends", response);
JSONArray jResult = responseObj.getJSONArray("req_users");
Toast.makeText(MainActivity.this, jResult.toString(), Toast.LENGTH_SHORT).show();
for(int i = 0; i < jResult.length(); i++)
{
JSONObject jresponse = jResult.getJSONObject(i);
String profile = jresponse.getString("userid");
friendlist.add(profile);
}
for(int i = 0; i < friendlist.size(); i++)
requestimagelink(friendlist.get(i));
}
catch(JSONException e)
{
Log.d(TAG, "error" + e.getMessage());
Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse (VolleyError error)
{
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}
);
MyApplication.getInstance().addToRequestQueue(strReq);
}
private void requestimagelink (final String profilename)
{
//This snippet will prevent re-downloading
if(profile_img_Hash.get(profilename) != null) {
runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged(); //Optional. Not neccessary..!
}
});
return; //Because this profile's image is loaded.
}
String uri = String.format(Config.URL_REQUEST_IMAGE + "?userid=%1$s", profilename);
Toast.makeText(MainActivity.this, uri, Toast.LENGTH_SHORT).show();
Log.d(TAG, "uri" + uri);
StringRequest strReq = new StringRequest(
Request.Method.GET,
uri,
new Response.Listener<String>()
{
//response from the server
#Override
public void onResponse (String response)
{
try
{
JSONObject responseObj = new JSONObject(response);
((TextView) findViewById(R.id.tvprofilejson)).setText(response);
Log.d(TAG, response);
JSONArray jResult = responseObj.getJSONArray("photos");
for(int i = 0; i < jResult.length(); i++)
{
JSONObject jresponse = jResult.getJSONObject(i);
ImageClass img = new ImageClass();
img.setThumbnailUrl(jresponse.getString("name"));
img.setTitle(profilename);
imageList.add(img);
//imagelinks.add(jresponse.getString("name"));
//Before notifying the adapter we have to put the img into our hash map.
profile_img_Hash.put(profilename, img);
//Remember, in you getView(..) method of your adapter, you have to get image from
// profile_img_Hash by profileName as key. If the returned result was null do nothing
// If the returned value was not null you can use the ImageClass to provide profile's
// image. :)
adapter.notifyDataSetChanged();
}
}
catch(JSONException e)
{
Log.d(TAG, "error" + e.getMessage());
Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse (VolleyError error)
{
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}
);
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(strReq);
}
Keep in mind, in your arrayAdapter's getView(...) method you must load profile's image right from profile_img_Hash with profile name as key like this:
ImageClass img = profile_img_Hash.get(profilename);
if(img != null){
//row's imageView.setBitmap(img.getBitmap());
}
Hope this helps.
Ways to implement volley json response cache.I tried the following way to get response from volley.i get the response correctly.I dont know how to store these json values into volley cache
StringRequest strReq = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("mainresp$$$"+response);
Log.d("Volley Request Success", response.toString());
result=response;
callback.onSuccess(result);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("volley request Error",
"Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
Together with my comments, you have already read my answer at the following question:
Android Setup Volley to use from Cache
I have just tested with POST request, as the following code:
CacheRequest cacheRequest = new CacheRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
try {
final String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
// Check if it is JSONObject or JSONArray
Object json = new JSONTokener(jsonString).nextValue();
JSONObject jsonObject = new JSONObject();
if (json instanceof JSONObject) {
jsonObject = (JSONObject) json;
} else if (json instanceof JSONArray) {
jsonObject.put("success", json);
} else {
String message = "{\"error\":\"Unknown Error\",\"code\":\"failed\"}";
jsonObject = new JSONObject(message);
}
textView.setText(jsonObject.toString(5));
} catch (UnsupportedEncodingException | JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// do something...
}
});
My sample Asp.Net Web API code as the following:
// POST api/<controller>
public IHttpActionResult Post()
{
string jsonString = "[" +
"{" +
"name: \"Person 1\"," +
"age: 30," +
"type: \"POST\"," +
"}," +
"{" +
"name: \"Person 2\"," +
"age: 20," +
"type: \"POST\"," +
"}," +
"{" +
"name: \"Person 3\"," +
"age: 40," +
"type: \"POST\"," +
"}" +
"]";
JArray jsonObj = JArray.Parse(jsonString);
return Ok(jsonObj);
}
Here is the result screenshot