Volley Offline Working - android

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

Related

How to set object to VolleyRequest(POST Request) in this type of API?

I have an API link to send post request for creating the order,
I tried to set Request in this way.
I want to send POST request same as request to send in my image (Postman).
I want to create order from cart using cartID and index of the cart, how to send please help me out from this.
Thank You :
public void postCreateOrderByCustomer(ArrayList<CartItem> cartItems) {
String token = sharedPreferences.getString(Constant.token, null);
String endPoint = "https://prettyyou.in/cake/pos/api/customers/create-order?token=" + token;
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
Map<String, String> payloadParams = new HashMap<String, String>();
for (int i = 0; i < cartItems.size(); i++) {
payloadParams.put("cart[" + i
+ "][id]", cartItems.get(i).getId());
}
Log.d(TAG, "postCreateOrderByCustomer: " + jsonObject);
System.out.println("endPointCartGet" + " " + endPoint.toString());
jsonObject = new JSONObject(payloadParams);
Log.d(TAG, "postCreateOrderByCustomer: " + jsonObject);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, endPoint, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.d(TAG, "onResponseCustomer: " + response);
if (response.getBoolean("status")) {
Constant.orderId = response.getString("order_id");
Intent intent = new Intent(DeliveryDetailsActivity.this, PaymentDetailsActivity.class);
startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse: " + error.toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return payloadParams;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return super.getHeaders();
}
};
RequestQueue queue = Volley.newRequestQueue(DeliveryDetailsActivity.this);
queue.add(jsonObjectRequest);
}
You can also use Stringrequest and object request or Jsonobject requst

How to implement Nested JsonObject /JsonArrey in One Json Value?

I have a Json Format
Json Url
http://inter.youdao.com/intersearch?tag=simple-eh&from=en&to=hi&q=spin
I need only first i
first i - n. घुमाव; चक्रण; झुकाव
second i. v. घूमना; कातना
Is it possible that first i + second i word only first word = n. घुमाव, v. घूमना
The problem was showing result in android no eh velue.
How to get hindi word.
Json Result
{
"data": {
"eh": {
"": "spɪn",
"ukphone": "spɪn",
"ukspeech": "spin&type=1",
"trs": [
{
"i": "n. घुमाव; चक्रण; झुकाव"
},
{
"i": "v. घूमना; कातना"
}
],
Android Implement :
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
urlJsonObj, null, new Response.Listener<JSONObject>() { #Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
// Parsing json object response
// response will be a json object
JSONObject result = response.getJSONObject("data");
String eh= result.getString("eh");
JSONObject result1 = response.getJSONObject("eh");
String hindi= result1.getString("trs");
jsonResponse = "";
jsonResponse += "Hindi: " + hindi ;
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();
// hide the progress dialog
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
finally fix the Problem
Thanks
here is code :
try {
// Parsing json object response
// response will be a json object
String syncresponse = response.getString("data");
JSONObject object2 = new JSONObject(syncresponse);
String synckey = object2.getString("eh");
JSONObject object3 = new JSONObject(synckey);
JSONArray jArray1 = object3.getJSONArray("trs");
for(int i = 0; i < jArray1 .length(); i++)
{
JSONObject object4 = jArray1.getJSONObject(i);
String comp_id = object4.getString("i");
String replace = object4.getString( "i" ).replace( ";", "," );
translate.setText(mWord + "=" + comp_id);
}

How can I get a JSON value from Volley response?

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 am trying to get the value using JSON in android, Below is my code, It shows null pointer exception and error during request queue

/**
* 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);

Updating TextView-Text and fill it with internet data

I have a Listview with textviews. On a click on the convertview, the method is called:
private void getAmountFromItem() {
String url = "http://192.168.192.200/getAmountFromItem.php?amount_id=" + amountIDTest;
Log.e("URLUZ", "is " + url);
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET,
url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
feedObj = (JSONObject) feedArray.get(i);
Log.e("COUNTS", " " + feedObj.getString("count"));
textView.setText(feedObj.getString("count") + " count yeah");
textView.invalidate();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
I tried to set the text within "runOnUiThread" or on "textView.post(new Runnable)... but these won't work.. Any suggestions?
You should see this "solution" (best practice for updating ui object from volley)

Categories

Resources