Volley Cache not get updated - android

Hi I am using volley jar in my android app to cache the json data for the offline mode.It works perfectly.Here is my code
Cache cache1 = AppController.getInstance().getRequestQueue().getCache();
Entry entry1 = cache1.get(URL);
if (entry1 != null) {
// fetch the data from cache
try {
data2 = new String(entry1.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data2));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
AppController.getInstance().getRequestQueue().getCache().remove(URL);
// making fresh volley request and getting json
JsonObjectRequest jsonReq1 = new JsonObjectRequest(Method.GET,
URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error:" + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq1);
}
private void parseJsonFeed(JSONObject response) {
try {
feedArray = response.getJSONArray("events");
for (int i = 0; i < feedArray.length(); i++) {
feedObj = (JSONObject) feedArray.get(i);
event_id.add(feedObj.getInt("event_id"));
event_desc.add(feedObj.getString("event_title"));
event_date.add(feedObj.getString("event_date"));
event_place.add(feedObj.getString("event_place"));
event_time.add(feedObj.getString("event_time"));
}
listView.setAdapter(new dataListAdapter(event_date,event_desc,event_place,event_time));
//Log.i("event1111", event.toString());
// Log.i("event2222", event2.toString());
Toast.makeText(getActivity(), "dataa"+event_id, 5000).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
my problem is that I got data.But When I updated json data,the cache data will not update.So how can I change cache data based on json data.Please help me thanks in advance :)

Set the cache header response of your server correctly, I think you need to change the max-age of the header or any custom configuration because Volley looks at the header then stores the response in the cache, here is how it dose:
headerValue = headers.get("Cache-Control");
if (headerValue != null) {
hasCacheControl = true;
String[] tokens = headerValue.split(",");
for (int i = 0; i < tokens.length; i++) {
String token = tokens[i].trim();
if (token.equals("no-cache") || token.equals("no-store")) {
return null;
} else if (token.startsWith("max-age=")) {
try {
maxAge = Long.parseLong(token.substring(8));
} catch (Exception e) {
}
} else if (token.equals("must-revalidate") || token.equals("proxy-revalidate")) {
maxAge = 0;
}
}
}
headerValue = headers.get("Expires");
if (headerValue != null) {
serverExpires = parseDateAsEpoch(headerValue);
}
serverEtag = headers.get("ETag");
// Cache-Control takes precedence over an Expires header, even if both exist and Expires
// is more restrictive.
if (hasCacheControl) {
softExpire = now + maxAge * 1000;
} else if (serverDate > 0 && serverExpires >= serverDate) {
// Default semantic for Expire header in HTTP specification is softExpire.
softExpire = now + (serverExpires - serverDate);
}
Cache.Entry entry = new Cache.Entry();
entry.data = response.data;
entry.etag = serverEtag;
entry.softTtl = softExpire;
entry.ttl = entry.softTtl;
entry.serverDate = serverDate;
entry.responseHeaders = headers;

Related

restapi casha store data but i want when i click on listview item all items from service they store in cacha

I apply cache but it works only one time when I click on first item it shows data after that when I click on another it shows same data how t fix it any guidelines
Here is my code
String URL = "http://facekart.azanic.com/Data_show_all_.php";
final ProgressDialog progressDialog = new ProgressDialog(getContext());
progressDialog.setMessage("Fetcing, please wait...");
progressDialog.show();
StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("result");//getting array
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
Itemssetget it = new Itemssetget();
it.setName(jsonObject1.getString("name"));
it.setPhonenumber_seller(jsonObject1.getString("phonenumber_seller"));
it.setPrice(jsonObject1.getString("price"));
it.setDiscountprice(jsonObject1.getString("discountprice"));
it.setUnits(jsonObject1.getString("units"));
it.setStock(jsonObject1.getString("stock"));
it.setId(jsonObject1.getString("key_auto"));
it.setImageurl("http://facekart.azanic.com/images/" + jsonObject1.getString("imageurl"));
if (it.getStock().toString().equals("In stock")) {
items_random.add(it);
}
}
if (!items_random.isEmpty() && getActivity() != null) {
myAdapter = new homebuyer_fruits_adapter(getActivity(), items_random, homebuyer.phone_number_shop);
myAdapter.notifyDataSetChanged();
Random_list.addHeaderView(random_v);
Random_list.setAdapter(myAdapter);
Random_list.setSmoothScrollbarEnabled(true);
loadingdataprogress.stopShimmerAnimation();
loadingdataprogress.setVisibility(View.INVISIBLE);
// Toast.makeText(getContext(),"ADDED",Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(getContext(), "Some error occurred -> " + volleyError, Toast.LENGTH_LONG).show();
;
}
}) {
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
try {
Cache.Entry cacheEntry = HttpHeaderParser.parseCacheHeaders(response);
if (cacheEntry == null) {
cacheEntry = new Cache.Entry();
}
final long cacheHitButRefreshed = 3 * 60 * 1000; // in 3 minutes cache will be hit, but also refreshed on background
final long cacheExpired = 24 * 60 * 60 * 1000; // in 24 hours this cache entry expires completely
long now = System.currentTimeMillis();
final long softExpire = now + cacheHitButRefreshed;
final long ttl = now + cacheExpired;
cacheEntry.data = response.data;
cacheEntry.softTtl = softExpire;
cacheEntry.ttl = ttl;
String headerValue;
headerValue = response.headers.get("Date");
if (headerValue != null) {
cacheEntry.serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);
}
headerValue = response.headers.get("Last-Modified");
if (headerValue != null) {
cacheEntry.lastModified = HttpHeaderParser.parseDateAsEpoch(headerValue);
}
cacheEntry.responseHeaders = response.headers;
final String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new String(jsonString), cacheEntry);
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}
#Override
protected void deliverResponse(String s) {
super.deliverResponse(s);
}
#Override
public void deliverError(VolleyError error) {
super.deliverError(error);
}
//adding parameters to send
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("s_number", homebuyer.phone_number_shop);
parameters.put("trig", "all");
return parameters;
}
};
RequestQueue rQueue = Volley.newRequestQueue(getContext());
rQueue.add(request);
Thanks in advance if any one help me in this I want every item click it shows data but first time it get from service second time it use from cache r any other method you can also suggest me How I smooth my app
I don't want to loading again and again

Getting Error : java.lang.ArrayIndexOutOfBoundsException: length=1; index=1

I have implemented search function to get details of clients but when i select the searched item it gives me an error of
java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
so on
This is my code i am using Json to search my clients details and storing in array but when i search the data and select it i get the above error. Please help me out .Thank You
public void RunSearchClientService() {
//progressDialog.show();
JsonObjectRequest postRequest = new JsonObjectRequest
(Request.Method.POST, Network.API_URL + "clients/search", api_parameter, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject result = ((JSONObject) response.get("data"));
JSONArray clients = (JSONArray) result.get("clients");
JSONArray invoice_lines = (JSONArray) result.get("invoice_lines");
Integer invoice_number = helper_string.optInt(result, "invoice_number");
logoImage = helper_string.optString(result, "logo");
if (invoice_number > 0) {
edit_invoice_number.setText(String.format("%04d", invoice_number));
toolbar.setTitle(String.format("INV-%04d", invoice_number));
}
array_list_clients.clear();
array_clients = new String[clients.length()];
Integer selected_client_index = 0;
if (clients.length() > 0) {
for (int i = 0; i < clients.length(); i++) {
JSONObject obj = clients.getJSONObject(i);
Client client = new Client();
client.Id = obj.optInt("id");
client.UserId = obj.optInt("user_id");
client.Name = helper_string.optString(obj, "name");
client.Reg_Num = obj.optString("reg_num");
client.Email = helper_string.optString(obj, "email");
client.Address1 = helper_string.optString(obj, "address1");
client.Address2 = helper_string.optString(obj, "address2");
client.City = helper_string.optString(obj, "city");
client.State = helper_string.optString(obj, "state");
client.Postcode = helper_string.optString(obj, "postcode");
client.Country = helper_string.optString(obj, "country");
array_list_clients.add(client);
array_clients[i] = client.Name + " " + "Reg No. : "+ client.Reg_Num ;
if (currentInvoice != null && currentInvoice.ClientId == client.Id) {
selected_client_index = i;
currentClient = client;
}
/*if (obj.optInt("invoice_number") > 0)
invoice_number = obj.optInt("invoice_number");*/
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(NewInvoiceActivity.this, R.layout.custom_simple_spinner_item, array_clients);
spinner_client.setAdapter(adapter);
spinner_client.setSelection(selected_client_index);
}
if (invoice_lines.length() > 0) {
for (int i = 0; i < invoice_lines.length(); i++) {
JSONObject obj = invoice_lines.getJSONObject(i);
Item item = new Item();
item.Id = obj.optInt("id");
item.Quantity = obj.optInt("quantity");
item.Name = helper_string.optString(obj, "name");
item.Rate = obj.optDouble("rate");
item.Description = helper_string.optString(obj, "description");
array_list_items.add(item);
}
calculate_total();
setListViewHeightBasedOnChildren(list_items);
}
if (array_list_items_from_intent != null && array_list_items_from_intent.size() > 0) {
for (int i = 0; i < array_list_items_from_intent.size(); i++) {
array_list_items.add(array_list_items_from_intent.get(i));
}
calculate_total();
setListViewHeightBasedOnChildren(list_items);
}
} catch (Exception ex) {
Toast.makeText(NewInvoiceActivity.this, R.string.error_try_again_support, Toast.LENGTH_LONG).show();
}
// if (progressDialog != null && progressDialog.isShowing()) {
// // If the response is JSONObject instead of expected JSONArray
// progressDialog.dismiss();
// }
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
if (progressDialog != null && progressDialog.isShowing()) {
// If the response is JSONObject instead of expected JSONArray
progressDialog.dismiss();
}
NetworkResponse response = error.networkResponse;
if (response != null && response.data != null) {
try {
JSONObject json = new JSONObject(new String(response.data));
// Toast.makeText(NewInvoiceActivity.this, json.has("message") ? json.getString("message") : json.getString("error"), Toast.LENGTH_LONG).show();
} catch (JSONException ex) {
Toast.makeText(NewInvoiceActivity.this, R.string.error_try_again_support, Toast.LENGTH_SHORT).show();
}
} else {
// Toast.makeText(NewInvoiceActivity.this, error != null && error.getMessage() != null ? error.getMessage() : error.toString(), Toast.LENGTH_LONG).show();
}
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("X-API-KEY", MainActivity.api_key);
return params;
}
};
// Get a RequestQueue
RequestQueue queue = MySingleton.getInstance(NewInvoiceActivity.this).getRequestQueue();
//Used to mark the request, so we can cancel it on our onStop method
postRequest.setTag(TAG);
MySingleton.getInstance(NewInvoiceActivity.this).addToRequestQueue(postRequest);
}
The error ArrayIndexOutOfBoundsException: length=1; index=1 means your array at index 1 is not valid; in other words, you are trying to access the second element of an array that has only one element.
The below code will give a similar error:
public class ReplicateError {
public static void main(String args[]) {
// reproducing java.lang.ArrayIndexOutOfBoundsException : 1 error
String[] clients = {"John"};
String client = clients[1];
// this will throw java.lang.ArrayIndexOutOfBoundsException : 1
System.out.println(client);
}
}
I suggest you do a bound check:
if (args.length < 2) {
System.err.println("Not enough arguments received.");
return;
}

Handle response of multiple request from Volley Library

I am sending multiple request through for loop.
On response I get success or failure message, and I need to show this message in a AlertDialog.
My Problem is: when I am sending 10 request then I am getting 10 response hence 10 times dialogue is showing with response.
I want to show only one dialogue when all response will have come,and that dialogue should contain response according to their each and every request.
How can I do it.
code which I tried:
if (globalInstance.isNetworkAvailable(AddBookingList.this)) {
int si = checkedItems.size();
if (checkedItems.size() > 0) {
for (int i = 0; i < si; i++) {
int appid = checkedItems.get(i).getAppid();
int bookingId = checkedItems.get(i).getBookingid();
List<Contacts> con = db.getadvertisment(bookingId);
List<AddImages> img = db.getImagesbybookingId(bookingId);
String postXml = createxmlForPost(con, img);
sendDataToServer(postXml,appid, bookingId, si);
}
}
}
private void sendDataToServer(final String postXml, final int appid, final int bookingId, final int si) {
final ProgressDialog progressDialog = new ProgressDialog(this, R.style.AppCompatAlertDialogStyle);
progressDialog.setMessage("Please wait...");
progressDialog.setCancelable(false);
progressDialog.show();
try {
final RequestQueue queue = Volley.newRequestQueue(this);
JSONObject obj = new JSONObject();
obj.put("xmlData", postXml);
int socketTimeout = 30000;//30 seconds
final StringRequest postRequest = new StringRequest(Request.Method.POST, Constants.Rootpath + "PostBooking",
new Response.Listener<String>() {
#Override
public void onResponse(String st) {
if (progressDialog != null || progressDialog.isShowing()) {
progressDialog.dismiss();
}
try {
JSONArray response = new JSONArray(st);
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
int status = jsonObject.getInt("Status");
String msg = jsonObject.getString("Msg");
String serverbooking_id = jsonObject.getString("BookingId");
if (status == 1) {
checkedItems.clear();
if (response.length() > 1) {
String newserverbooking_id = response.getJSONObject(0).getString("BookingId") + "\n" + response.getJSONObject(1).getString("BookingId");
db.updateBookingDetailsbyAppId(newserverbooking_id, appid, status);
} else {
db.updateBookingDetailsbyAppId(serverbooking_id, appid, status);
}
showDatainList();
globalInstance.showSuceessMessage(true, "Success!!! Your BookingID is: " + serverbooking_id, AddBookingList.this);
try {
List<Contacts> contacts = db.getAllBookingDetails();
for (int h = 0; h < contacts.size(); h++) {
locallySaveImagesinPhone(bookingId, contacts.get(h).get_serverbookingId());
}
} catch (IOException e) {
e.printStackTrace();
}
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
} else {
globalInstance.showFailureMessage(false, "Booking Failed." + msg, AddBookingList.this);
checkedItems.clear();
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (progressDialog != null || progressDialog.isShowing()) {
progressDialog.dismiss();
}
String msg = error.getMessage();
globalInstance.showFailureMessage(false, "Booking Failed.Please Try Again!!!", AddBookingList.this);
}
}
) {
#Override
protected Map<String, String> getParams() {
HashMap<String, String> params = new HashMap<>();
params.put("xmldata", postXml);
return params;
}
};
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
postRequest.setRetryPolicy(policy);
queue.add(postRequest);
} catch (JSONException e1) {
e1.printStackTrace();
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
As i understand your problem is calling globalInstance.showSuceessMessage() or globalInstance.showFailureMessage every time you get the response.
what i think might work is:
Instead of these two methods, define an Arraylist<String> and based on the
success or failure of the response add messages to it like "Success!!! Your BookingID is: " + serverbooking_id and "Booking Failed." + msg.
Define a method like showMessages() which has a dialogue containing the messages u added to arraylist before. then call it after where you called thesendDataToServer method which is in the if (checkedItems.size() > 0) block.

Cache.Entry not getting json data

I'm using volly to retrieve data and its work perfectly, except that my json array is not storing in the cache.
Here is my code:
private void getCacheValue() {
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Cache.Entry entry = cache.get(Endpoints.product_url);
if(entry != null){
Log.w("Logdata:", ""+ entry.toString());
try {
String data = new String(entry.data, "UTF-8");
JSONArray jsonArray = new JSONArray(data);
// handle data, like converting it to xml, json, bitmap etc.,
Log.v("Hello", data);
listProduct.clear();
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject object = jsonArray.getJSONObject(i);
ItemCategories image = new ItemCategories();
image.setCategoryItem(object.getString(key_title));
image.setUrlThumb(object.getString(key_image));
listProduct.add(image);
} catch (JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
}
}
adapterProductList.notifyDataSetChanged();
progressBarMain.setVisibility(View.GONE);
internetError.setVisibility(View.GONE);
recycleProductList.setVisibility(View.VISIBLE);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
Log.v("JSON EXCEPTION", "DECLINE");
}
} else {
if(isNetworkAvailable()) {
fetchImages();
} else {
progressBarMain.setVisibility(View.GONE);
internetError.setVisibility(View.VISIBLE);
}
}
}
private void fetchImages() {
JsonObjectRequest jsObjRequest =
new JsonObjectRequest(Request.Method.GET, Endpoints.product_url(String) null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
listProduct.clear();
try {
JSONArray routes = response.getJSONArray(key_product);
for (int i = 0; i < routes.length(); i++) {
JSONObject object = routes.getJSONObject(i);
ItemCategories categories = new ItemCategories();
categories.setCategoryItem(object.getString(key_title));
categories.setUrlThumb(object.getString(key_image));
listProduct.add(categories);
}
adapterProductList.notifyDataSetChanged();
progressBarMain.setVisibility(View.GONE);
internetError.setVisibility(View.GONE);
recycleProductList.setVisibility(View.VISIBLE);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsObjRequest);
}
I have already declared Appcontroller in the manifest, but I don't know why caching is not working.
Here is my json_data
fetchImage() is working because there is data in recyclerview. However, when I try to retrieve the data offline it does show any because my cache can't store any data.
By default, Volley only caches data if Response Header permits.
Volley caches response on the basis of following response headers:
1. Cache-Control
2. Expires
3. maxAge
See below function for details :
public static Cache.Entry parseCacheHeaders(NetworkResponse response) {
long now = System.currentTimeMillis();
Map<String, String> headers = response.headers;
long serverDate = 0;
long lastModified = 0;
long serverExpires = 0;
long softExpire = 0;
long finalExpire = 0;
long maxAge = 0;
long staleWhileRevalidate = 0;
boolean hasCacheControl = false;
boolean mustRevalidate = false;
String serverEtag = null;
String headerValue;
headerValue = headers.get("Date");
if (headerValue != null) {
serverDate = parseDateAsEpoch(headerValue);
}
headerValue = headers.get("Cache-Control");
if (headerValue != null) {
hasCacheControl = true;
String[] tokens = headerValue.split(",");
for (int i = 0; i < tokens.length; i++) {
String token = tokens[i].trim();
if (token.equals("no-cache") || token.equals("no-store")) {
return null;
} else if (token.startsWith("max-age=")) {
try {
maxAge = Long.parseLong(token.substring(8));
} catch (Exception e) {
}
} else if (token.startsWith("stale-while-revalidate=")) {
try {
staleWhileRevalidate = Long.parseLong(token.substring(23));
} catch (Exception e) {
}
} else if (token.equals("must-revalidate") || token.equals("proxy-revalidate")) {
mustRevalidate = true;
}
}
}
headerValue = headers.get("Expires");
if (headerValue != null) {
serverExpires = parseDateAsEpoch(headerValue);
}
headerValue = headers.get("Last-Modified");
if (headerValue != null) {
lastModified = parseDateAsEpoch(headerValue);
}
serverEtag = headers.get("ETag");
// Cache-Control takes precedence over an Expires header, even if both exist and Expires
// is more restrictive.
if (hasCacheControl) {
softExpire = now + maxAge * 1000;
finalExpire = mustRevalidate
? softExpire
: softExpire + staleWhileRevalidate * 1000;
} else if (serverDate > 0 && serverExpires >= serverDate) {
// Default semantic for Expire header in HTTP specification is softExpire.
softExpire = now + (serverExpires - serverDate);
finalExpire = softExpire;
}
Cache.Entry entry = new Cache.Entry();
entry.data = response.data;
entry.etag = serverEtag;
entry.softTtl = softExpire;
entry.ttl = finalExpire;
entry.serverDate = serverDate;
entry.lastModified = lastModified;
entry.responseHeaders = headers;
return entry;
}
You can change default cache policy by overriding Request object.
You can override JsonObjectRequest like :
public class CustomJsonObjectRequest extends JsonObjectRequest {
public CustomJsonObjectRequest(int method, String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(method, url, jsonRequest, listener, errorListener);
}
public CustomJsonObjectRequest(String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(url, jsonRequest, listener, errorListener);
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
return Response.success(new JSONObject(jsonString),
parseIgnoreCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
public static Cache.Entry parseIgnoreCacheHeaders(NetworkResponse response) {
long now = System.currentTimeMillis();
Map<String, String> headers = response.headers;
long serverDate = 0;
String serverEtag = null;
String headerValue;
headerValue = headers.get("Date");
if (headerValue != null) {
serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);
}
serverEtag = headers.get("ETag");
final long cacheHitButRefreshed = 3 * 60 * 1000; // in 3 minutes cache will be hit, but also refreshed on background
final long cacheExpired = 24 * 60 * 60 * 1000; // in 24 hours this cache entry expires completely
final long softExpire = now + cacheHitButRefreshed;
final long ttl = now + cacheExpired;
Cache.Entry entry = new Cache.Entry();
entry.data = response.data;
entry.etag = serverEtag;
entry.softTtl = softExpire;
entry.ttl = ttl;
entry.serverDate = serverDate;
entry.responseHeaders = headers;
return entry;
}
}
Update your fetchImage function as:
private void fetchImages() {
CustomJsonObjectRequest jsObjRequest = new CustomJsonObjectRequest()
(Request.Method.GET, Endpoints.product_url, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
listProduct.clear();
try {
JSONArray routes = response.getJSONArray(key_product);
for (int i = 0; i < routes.length(); i++) {
JSONObject object = routes.getJSONObject(i);
ItemCategories categories = new ItemCategories();
categories.setCategoryItem(object.getString(key_title));
categories.setUrlThumb(object.getString(key_image));
listProduct.add(categories);
}
adapterProductList.notifyDataSetChanged();
progressBarMain.setVisibility(View.GONE);
internetError.setVisibility(View.GONE);
recycleProductList.setVisibility(View.VISIBLE);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsObjRequest);
}
For reference, check Android Volley + JSONObjectRequest Caching

How to refresh my ListView?

public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private String URL_FEED = "http://myozawoo.esy.es/data.php";
private String URL_FEED2 = "http://api.androidhive.info/feed/feed.json";
private SwipeRefreshLayout swipeContainer;
// String page = getIntent().getExtras().getString("page");
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 0);
setContentView(R.layout.activity_main);
// String page = getIntent().getExtras().getString("page");
swipeContainer = (SwipeRefreshLayout) findViewById(R.id.swipeContainer);
swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
parseJsonFeed();
}
});
listView = (ListView) findViewById(R.id.list);
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(this, feedItems);
listView.setAdapter(listAdapter);
// These two lines not needed,
// just to get the look of facebook (changing background color & hiding the icon)
// getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
// getActionBar().setIcon(
// new ColorDrawable(getResources().getColor(android.R.color.transparent)));
// We first check for cached request
// Cache cache = AppController.getInstance().getRequestQueue().getCache();
// Page One
String page = getIntent().getExtras().getString("page");
if(page.equals("1")) {
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(URL_FEED);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, 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);
}
}
//Page Two
else if (page.equals("2")) {
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(URL_FEED2);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
URL_FEED2, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, 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);
}
}
// Other Four Pages
else {
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(URL_FEED);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, 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);
}
}
swipeContainer.setColorSchemeColors(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
}
/**
* Parsing json reponse and passing the data to feed view list adapter
* */
public void parseJsonFeed(JSONObject response) {
try {
// String page = getIntent().getExtras().getString("page");
// if (page.equals("1"))
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
final FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
swipeContainer.setRefreshing(false);
}
}
I want to refresh my ListView. Now, I can't refresh. I don't know how to refresh. How to do in onRefresh(){}. I can't call parseJSON() to onRefresh(){}. Please tell me someone. Thanks you very much! :-)
In your page change call, use adapter to clear the items in ListView
listAdapter.clear();
adapter.notifyDataSetChanged();
If you are using a custom adapter that extends Android ArrayAdapter, you may not find .clear() because private class varies depending on implementation. For instance, .update()
Anyway, try make changes here and see if it works.
swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
// ---- RIGHT HERE THIS LINE
listAdapter.notifyDataSetChanged();
}
});
You have used adaper on list view as
listAdapter = new FeedListAdapter(this, feedItems);
listView.setAdapter(listAdapter);
Now after updating its value you can call
listAdapter.notifyDataSetChanged();
You are looking for method to refresh list view data then its method available in adapter notifyDataSetChanged();
In hour pareseJsonFeed update with
it...
/**
* Parsing json reponse and passing the data to feed view list adapter
* */
public void parseJsonFeed(JSONObject response) {
try {
// String page = getIntent().getExtras().getString("page");
// if (page.equals("1"))
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
final FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
listAdapter.clear();
listAdapter.addAll(feedItems);
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
swipeContainer.setRefreshing(false);
}
}
Try to invalidate your cached data this is when you're calling again to the server. It is the last call in AppController.getInstance().getRequestQueue().getCache().invalidate(key,boolean)

Categories

Resources