Android : How to use Cache in ion library? - android

In my case, I want to load data from Cache. If there is cache load from cache else load from network. How can I use caching in Ion?
private void loadION() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("loading");
progressDialog.show();
Ion.with(getApplicationContext()).load(url)
.setBodyParameter("tag", "annual_schedule").asString()
.setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String str) {
Message.Toast(getApplicationContext(), str);
progressDialog.dismiss();
}
});
}

Ion will automatically cache GET requests. This is a POST request, and can not be cached by the library.
Furthermore, cached requests can't be used right away, since disk I/O is still treated as a blocking call. It will still be an asynchronous request.

Related

Callback call with Ion on Intent Service(android)

In my application I want to send my recordings to the web site on backgroud. I've researched and I reached the conclusion that I should use and IntentService.
But this leads me to a problem, i cannot reach the callback of Ion inside the IntentService.
The callback is important because I want to delete the file after finishing the upload.
How can I make this?
This is my code:
Ion.with(this)
.load(ip_address)
.setMultipartParameter("key", key)
.setMultipartFile("audio_file", array_mp3[idx])
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
#Override
public void onCompleted(Exception e, JsonObject result) {
Log.d("BackS", "wifiteste - chega aqui ");
array_mp3[idx].delete();
}
});
I never reach that Log which means that i never delete the file.
Thanks in advance.

How to observe for changes in web service and update ui using RxAndroid?

What I want to achieve is to be able to observe changes in my web service and then update my textview if there is any change. I am currently using timer to achieve this by running it every x second. The problem though, is that the memory leaks so it's not a good solution. Now I stumbled upon this rxjava/rxjava but I'm confused on how to use it. The documentation is confusing to me and I can't find alot of tutorials about this. I am using volley to get data from my web service by the way.
this is the Observable that someone on answered on my other question but I'm getting an error which is "Incompatible types" on return sendRequest.
Observable.interval(500, TimeUnit.MILLISECONDS, Schedulers.io()).map(new Func1<Long, Object>() {
#Override
public Object call(Long tick) {
return sendRequest();
}
}).observeOn(AndroidSchedulers.mainThread()).subscribe();
here is my volley request code
public void sendRequest(){
//While the app fetched data we are displaying a progress dialog
//final ProgressDialog loading = ProgressDialog.show(this,"Fetching Data","Please wait...",false,false);
StringRequest stringRequest = new StringRequest(JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//text.setText(response);
//loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
requestQueue.add(stringRequest);
}
private void showJSON(String json){
ParseJson pj = new ParseJson(json);
pj.parseJSON();
text.setText(ParseJson.playing[0]);
}
Your method sendRequest doesn't return anything(void). You can either return null or something.
#Override
public Object call(Long tick) {
sendRequest();
return null;
}
I would suggest you firstly read Java basics instead of writing Android app.
Use push notifications to send messages from the server to the users when data is updated and avoid sending unwanted requests to the server.
Then you can send the request for new data only when notified and update the Observer someway, maybe use a rx subject, or better store the data in SQLite table and observe changes from the DB.
Recommend this to create a rx stream from sqlite
https://github.com/square/sqlbrite
GCM: https://developers.google.com/cloud-messaging/

Ion Android getHeaders

How do I get a specific header using the Ion network library for Android?
This is what I'm trying:
...
.setCallback(new FutureCallback<Response<String>>() {
#Override
public void onCompleted(Exception e, Response<String> result) {
System.out.println("header: " + result.getHeaders().message("mykey"));
}
});
message(String) sets the HTTP response message. I should make that internal to avoid confusion.
Use
getHeaders().getHeaders().get(String)
It's a bit obtuse at the moment, will need to clean that API up in the next release.

Android Volley store requests when offline

I've searched all over but haven't found an answer to this.
In my Android application, the user can use the app offline, and some events generate http GET requests to my server. I am using Volley, and when the user is online the requests work properly, but offline they fail immediately and are removed from the request queue.
I wanted Volley to store these requests, and try again when the server is accessible, or at least keep trying. Is this behaviour possible?
Here's how I'm doing things:
StringRequest request = new StringRequest(Request.Method.GET, url, listener, listener);
request.setRetryPolicy(new DefaultRetryPolicy(8000, 2, 1.5f));
postToDefaultQueue(request);
private void postToDefaultQueue (StringRequest request) {
if (sQueue == null) {
sQueue = Volley.newRequestQueue(mContext.get());
}
sQueue.add(request);
}
Thanks so much, any help appreciated
Edit
So I managed to make the request go back to the queue after it fails. The code is below:
private class DummyListener implements Response.Listener<String>, Response.ErrorListener {
String mUrl;
public DummyListener (String url){
mUrl = url;
}
#Override
public void onErrorResponse(final VolleyError error) {
new Timer().schedule(new TimerTask() {
#Override
public void run() {
Log.v(DummyListener.class.getSimpleName(), "ErrorResponse", error);
offlineStringGetRequest(mUrl);
}
}, 5000);
}
#Override
public void onResponse(String response) {
Log.d(DummyListener.class.getSimpleName(), "Response: " + response);
}
}
The problem that remains is that if I kill the app, the queue gets destroyed, and the request is never made.
Edit2
Noticed some people liked this question. I ended up using Path (https://github.com/path/android-priority-jobqueue) with some modifications for the job. It worked perfectly. Just wish Volley had a native way for doing this
Since I found no way to do this with Volley, I ended up using Path
And it worked wonders

Android Server communication asynchronously

I am working on an asynchronous client server application. After a request is made to a server asynchronously, I should process the message and send back to the client. To receive the response from the server asynchronously, the client should have a sort of RESTful server. Are there any libraries or APIs I can use on android client?
Thanx
Use Retrofit by Square.
(From the site:)
Introduction
Retrofit turns your REST API into a Java interface.
public interface GitHubService {
#GET("/users/{user}/repos")
List<Repo> listRepos(#Path("user") String user);
}
The RestAdapter class generates an implementation of the GitHubService interface.
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("https://api.github.com")
.build();
GitHubService service = restAdapter.create(GitHubService.class);
Each call on the generated GitHubService makes an HTTP request to the remote webserver.
List<Repo> repos = service.listRepos("octocat");
Use annotations to describe the HTTP request:
URL parameter replacement and query parameter support
Object conversion to request body (e.g., JSON, protocol buffers)
Multipart request body and file upload
Also try to avoid AsyncTask, this is a good read on the subject: Robust and readable architecture for an Android App
Actually don't use Asynctask - it's lacks important features needed for a proper network framework (or you just sit and develop them yourself for hours)
Google developed Volley for that in 2013:
Volley automatically schedule all network requests. It means that Volley will be taking care of all the network requests your app executes for fetching response or image from web.
Volley provides transparent disk and memory caching.
Volley provides powerful cancellation request API. It means that you can cancel a single request or you can set blocks or scopes of requests to cancel. Volley provides powerful customization abilities.
Volley provides Debugging and tracing tools
(from: Android – Volley Library Example)
Resources
Google IO 13 presentation
Official Google Repo
Github mirror
Gradle Dependency
compile 'com.mcxiaoke.volley:library:1.0.+'
You can use AsyncTask for the same,
here is official documentation http://developer.android.com/reference/android/os/AsyncTask.html
I am also giving you an example of Asyntask.
class TestAsyncTask extends AsyncTask<Void, Integer, String>
{
protected void onPreExecute (){
Log.d("ASYNCTASK","On pre Exceute......");
}
protected String doInBackground(Void...arg0) {
Log.d("ASYNCTASK","In On doInBackground...");
// make request RESTful service here.
for(int i=0; i<10; i++){
Integer in = new Integer(i);
publishProgress(i); // Update your Ui
}
return "You are in PostExecute";
}
protected void onProgressUpdate(Integer...a){
Log.d("ASYNTASK","You are in progress update ... " + a[0]);
}
protected void onPostExecute(String result) {
// here you can perform all action after getting resonances from RESTful service
Log.d(""+result);
}
}
Try to implement code like this:
ProgressDialog progressDialog=null;
private class LoadApi extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
progressDialog=ProgressDialog.show(YourActivity.this, "",
"Please wait...");
super.onPreExecute();
}
protected String doInBackground(String... urls) {
//Do your api call stuff here
return null;
}
protected void onPostExecute(String result) {
handle response from api call here.
progressDialog.dismiss();
}
}
If you needed a external library for http services.You can use Android Asynchronous Http Client
http://loopj.com/android-async-http/
downloaded the jar file from the link use this method
public void getData(String URL)
{
AsyncHttpClient client = new AsyncHttpClient();
client.setTimeout(30000);
client.get(URL, new AsyncHttpResponseHandler()
{
#Override
public void onSuccess(String arg0)
{
// TODO Auto-generated method stub
super.onSuccess(arg0);
}
#Override
public void onFailure(Throwable arg0, String arg1)
{
// TODO Auto-generated method stub
super.onFailure(arg0, arg1);
}
});
}
You got the result as a string in the onsucess.
in your manifest file u have to given the permission
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

Categories

Resources