Volley won't cache my requests - android

I am trying to cache data for offline usage without success. Below is my work so far.
//fetch news details
private void FetchHeadline(){
showDialog();
btnRefresh.setVisibility(View.GONE);
// We first check for cached request
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(NEWS_URL);
if (entry != null) {
Log.e("", "babaaaaaaaaaaaaaaaaaaaaaaaa");
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONArray(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonArrayRequest jsonReq = new JsonArrayRequest(
NEWS_URL + dbHelper.getAuth().getString(0), new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
hideDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
btnRefresh.setVisibility(View.VISIBLE);
hideDialog();
Log.e(TAG, "Response: " + error.getMessage());
try {
if (error.getMessage().equalsIgnoreCase("java.io.IOException: No authentication challenges found")){
moveToLoginActivity();}
}catch(Exception e){}
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
I added the following to my .htaccess with no success
<IfModule headers_module>
# 1 Month for most static assets
<filesMatch ".(css|jpg|jpeg|png|gif|js|ico)$">
Header set Cache-Control "max-age=36000, public"
</filesMatch>
</IfModule>

Related

Error null! from Volley on Http Post Request with JSon object

I'm getting a Null Exception with JSon object from Volley
I filled the JSon object before it is used, and not in the parameterlist.
public static void SendPost6(final Context context){
final String TAG= "-->Error-->";
String url = "http://192.168.44.120/test_php_neuer_user.php";
RequestQueue queue = Volley.newRequestQueue(context);
JSONObject userObject = new JSONObject();
JSONObject paramsObject = new JSONObject();
try {
paramsObject.put("name", "Name");
paramsObject.put("email", "EMail");
userObject.put("user",paramsObject);
}
catch (JSONException e){
Toast.makeText(context, "JSON-Error:" + e.toString(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url,
userObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(context, "Volley Response:" + response.toString(), Toast.LENGTH_LONG).show();
}},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//handle errors#
Log.d(TAG, "Failed with error msg:\t" + error.getMessage());
Log.d(TAG, "Error StackTrace: \t" + error.getStackTrace());
Toast.makeText(context, "Volley Error:" + error.getMessage(), Toast.LENGTH_LONG).show();
error.printStackTrace();
try {
byte[] htmlBodyBytes = error.networkResponse.data;
Log.e(TAG, new String(htmlBodyBytes), error);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
});
queue.add(request);
//AppController.getInstance().addToRequestQueue(request);
I want to add the json object request into the queue to perform http-post. Volley Error is "null"
The firewall blocked the network access. This is why i'm getting response null. Solved.

JSON parsing problem with Volley in Android?

This project used to work successfully before. After we changed URL from web service that don't parse data. We changed URL bus/search instead of bus.
This is where I send request and it run successfully with new URL. But this state is working and show this fault.
catch (JSONException e) {
Log.e("search" + owner + "VoyagesErr1", e.toString());
e.printStackTrace();
}
error: e: "org.json.JSONException:No value for status
Voyage.java
private void sendRequest(final String owner, final Map<String, String> header) {
//url = "http://12.1.1.12:1337/";
StringRequest stringRequest = new StringRequest(Request.Method.POST, MyConstants.URL + owner,
new Response.Listener<String>() {
#Override
// servisten 200 olarak bir veri alındığında onResponse içine düşüyor.
public void onResponse(String response) {
// Log.e("AAAA" + owner, response);
try {
JSONObject object = new JSONObject(response);
if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_NOTAVAILABLE)) {
sendVoyagesErrorBroadcast(owner, MyConstants.ERROR_NOTAVAILABLE);
} else if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_SUCCESS)) {
JSONArray result = object.getJSONArray(MyConstants.SERVICE_RESULT);
JSONArray resultGoing = result.getJSONObject(0).getJSONArray("going");
if (has_return) {
JSONArray resultReturn = result.getJSONObject(1).getJSONArray("round");
sendVoyagesArrayBroadcast(owner + MyConstants.DIRECTION_RETURN, resultReturn);
}
sendVoyagesArrayBroadcast(owner + MyConstants.DIRECTION_GOING, resultGoing);
} else if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_FAİLURE)) {
sendVoyagesErrorBroadcast(owner, MyConstants.ERROR_SERVER);
}
} catch (JSONException e) {
Log.e("search" + owner + "VoyagesErr1", e.toString());
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("AAAA" + owner, String.valueOf(error.getCause()));
sendVoyagesErrorBroadcast(owner, getErrorType(error));
}
It don't receive in this class.
MyBaseVoyageFragment.java
String broadcastTAG = BROADCAST_TAG + owner + String.valueOf(direction);
if (intent != null) { // put the receiving data on intent
Log.e("received", intent.getAction()); // succesfull action
String intentAction = intent.getAction();
if (intentAction.equals(broadcastTAG)) {
parseIntentDataAndLoadVoyagesAdapter = new ParseIntentDataAndLoadVoyagesAdapter(intent);
parseIntentDataAndLoadVoyagesAdapter.execute(""); // asenkron görevi çalıştır.
//loadVoyagesToAdapter();
} else if (intentAction.equals(BROADCAST_TAG + owner + "Error")) {
showLoadingDialog(false);
setErrorView(intent.getIntExtra("data", 0));
}
}

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)

Volley synchronous request

I just started to use Volley's library to make http calls, and I tried to use the RequestFuture class for synchronous requests, but I fail my attempt to make a simple request. Any idea of what I am doing wrong?
RequestQueue requestQueue = Volley.newRequestQueue(this);
String url = "http://myapi-oh.fr/v2/podcasts/x/shows/" + points.get(0).getShowId() + "/streams";
RequestFuture<JSONObject> future = RequestFuture.newFuture();
JsonObjectRequest request = new JsonObjectRequest(url, null, future, future);
requestQueue.add(request);
try {
JSONObject response = future.get(10, TimeUnit.SECONDS);; // this will block (forever)
points.get(0).setStreamUrl(response.getJSONArray("result").getJSONObject(0).getString("url"));
} catch (InterruptedException e) {
Log.d(TAG, "error : " + e);
// exception handling
Log.d(TAG, "error : " + e);
} catch (ExecutionException e) {
// exception handling
Log.d(TAG, "error : " + e);
} catch (JSONException e) {
e.printStackTrace();
Log.d(TAG, "error : " + e);
} catch (TimeoutException e) {
e.printStackTrace();
}
To make a simple request just use the StringRequest class. Below is a small snippet:
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest req = new StringRequest(Request.Method.POST, "your_url", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//handle response here.
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
//handle error here.
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//return params(if any) to server here.
return super.getParams();
}
};
queue.add(req);

volley cache is empty

Im working on with volley, i have issue in retrieving the cache. Every time I'll to access the cache for display It is empty. But when i check it on the sdcard I can see a files under cache folder in my application.
// We first check for cached request
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Cache.Entry entry = cache.get(URL_DASHBOARD);
AppController.getInstance().getRequestQueue().getCache().invalidate(URL_DASHBOARD, true);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
JSONObject temp = new JSONObject(data);
Log.e(TAG,"loadVolleyConnection: fetch data from cache: "+temp.toString());
setAdapter_dashboard(temp.getJSONArray(JSON_DASHBOARD.ARRAY_DASHBOARD.getVal().toString()));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
Log.e(TAG,"loadVolleyConnection: query to api “);
executeVolleyRequest(URL_DASHBOARD);
}
executeVolleyRequest
/**Execute Volley*/
private void executeVolleyRequest(String path){
//Making fresh volley request and getting json array
String tag_string_req = "string_req";
StringRequest stringRequest = new StringRequest(Request.Method.POST,path,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(TAG,"loadVolleyConnection: fetch data from api: "+response);
try {
JSONObject temp_obj = new JSONObject(response);
JSONArray temp_array = temp_obj.getJSONArray(JSON_DASHBOARD.ARRAY_DASHBOARD.getVal().toString());
setAdapter_dashboard(temp_array);
if(isRefreshed){
// Call onRefreshComplete when the list has been refreshed.
(myListView).onRefreshComplete();
isRefreshed = false;
setUpdate(temp_array);
Log.e(TAG,"loadVolleyConnection: isRefreshed..");
}else{
setAdapter_dashboard(temp_array);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e(TAG, "Error: " + volleyError.getClass().getSimpleName());
if (volleyError.networkResponse == null) {
if (volleyError.getClass().equals(TimeoutError.class)) {
// Show timeout error message
Alertmessage("Login Error","Oops.Timeout error!Please check your connection.");
}
}else{
Alertmessage("Login Error","Check your Connection./n");
}
//pDialog.dismiss();
}
}){
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(5000,2,1));
stringRequest.setShouldCache(true);
// Adding request to request queue
AppController.getInstance().addToRequestQueue(stringRequest, tag_string_req);
}
I can't figure out what i am missing.
thanks
After, testing for a couple of times, i found out that when you use volley and when you want to have a cache, you need to use a GET request not POST.
But my question is, is there a way that we can still use cache when using post?

Categories

Resources