Android Studio Asynctask Alternative - android

I'm new to Android Development, and I've run into this problem that I haven't found a solution for.
It starts off first with going to a webservice api for login. From there if the login is successful it executes to 2 functions for the actually data it needs, stores in sqlite and then proceeds to next activity. All 3 api requests are using AsyncTask and from what I understand my Activity is actually running faster than my "doInBackground" background thread. I want to know the path or what i should look into. I've read posts about using sleep, and read posts about how that is bad to do. I want to get the json data i need, store it, and use it immediately. I think i'm suppose to find away to connect directly and use a progress bar to get the data. Keep in mind, it's not a lot of data, but it's enough to stall my application.

Not sure what a ProgressBar has to do with retrieving data from a server but if you're looking for AsyncTask alternatives (particularly for HTTP calls) you can look at these frameworks (you'll probably only want to pick one):
Square's Retrofit
Google's Volley
Either one will make your life a lot easier when it comes to making HTTP requests. Their own documentation explains how to use them pretty well so I'm not going to go into how to use it here.
If you're looking for a native, lower level AsyncTask alternative, have a look at AsyncTaskLoaders. The AsyncTaskLoader essentially does exactly the same thing as an AsyncTask but they live within the life cycle of the Activity or Fragment so your code tends to be less error prone.

Related

Asynchronous requests to server posted in a loop - Android

I am a Java developer with no Android experience, and I am trying to quickly put an app together. It seems that what I would normally do in Java isn't helping.
At this stage, ease of implementation is more important than efficiency or style - I will sort the latter out when there is more time and I will have educated myself properly when it comes to Android.
People can use the app to ask for support, or offer it to those who need it. Asking for support posts a request with the details to the server, and that's done.
Now I would like the app to post an asynchronous request to the server, to be notified of outstanding support requests once a minute. I guess it's the same principle of WhatsApp checking if there is any new message on the server.
I tried doing that in a separate thread with an infinite loop which sleeps for 60 seconds but for some reasons that stops the UI from working.
From what I now understand, I should use a service with a Looper, a Timer and a Handler. Is that correct?
Could anybody point me to a tutorial which explains exactly what to do, step by step? Or at least suggest keywords I should look for?
All I found so far are snippets of code which don't work together when I try to assemble it. Possibly because I am not searching for the right terms?
Thanks, Dan
You could try the following approach:
Create a service that runs in the background to check for newly added data in the server.
If you prefer to make it user-driven, you can let users refresh the list on the device to actually trigger the requests to the server.
Libraries like Retrofit can make your life easier when it comes to making http requests - always avoid the main UI thread when doing this.
Another library that you could use to decouple your application using Events is EventBus. Assuming you are running a background service to check for updates, you can use EventBus to update your User Interfaces when something new is retrieved from the server through a GET request.
I hope this gives you an idea on how to proceed with the solution. Good luck!

Android REST API with RetroFit

My question is kinda theorical, hope I can get a clear explanation on this.
I've been looking for a nice rest api consumer for android (or some clear info on how to develop a solid one) and I found the rest api design talk from google IO 2010.
"Developing Android REST Client Applications - Google"
It's been 4 since this talk and I think there might exitst new designs and techniques for this matter, or not ?
The scenario that I think that would work the best for me is this one:
So my first question is, does this architecture is still valid for a new app (Starting from the beginning) ?
I've found Retrofit, which seems a pretty nice and stable Api for the rest service, but I can't quite understand how it works, like if it is a good approach to call my api endpoints from activities (or frags) and the library handles the resume/pause (delivering results when activity is on hold, or not) or I must implement this myself.
Sorry for the long post and thanks for the patience !
You must implement how to handle that yourself, to answer your question.
Yes, that architecture is valid, but RetroFit only forms part of the "Rest Method" block. How would you implement it? That depend on what you want. You could use Retrofit (AKA the REST Method) inside the service, and that would be ok, however you can also skip using services and use it inside of an activity or fragment. However if you do the second option(activities/fragments) you can not think in handling the activity life cycle within retrofit(onStart, onPause, etc..) because since these are network calls, you must perform them on worker threads(AsyncTasks for instance).
So in conclusion, whatever option you decide, being Services or worker threads, you must think in using perhaps observers to control your activity/fragment, and remember that requesting network data is always done out of the ui thread. Implementations of how to handle the situation may be done by you depending on your needs and complexity of the application.

What is the best threading choice in an Android application for a RESTful API passing JSON data?

I am new to Android. I’m attempting to write an application which will display multiple pieces of information about open stores. I get that information using a RESTfull API which passes JSON data.
Here is my question: What is the best service/threading implementation choice?
Here are my product requirements:
• I want to encapsulate all the API and JSON into a class that one or more Android “Activities” can call. I think this might dictate a service but this service will only need to run when my application is running and will not be accessible by other applications. The user will be required to authenticate into the remote system via the RESTfull API.
• It will have to be on a separate thread because of the possibility of the API calls taking too much time. I don’t think it will need to be multi-threaded since I don’t see more than one “Activity” will be interfacing with the service at a time.
• The service should look at caching some of the information it gets back so that when an “Activity” makes a call (“GetStoreList” for instance), it could return a list of stores it already queried earlier. I’m not sure if I should keep this information in memory or try using the SQLite functionality in Android. I could have several hundred stores in the list with ten to twelve other pieces of information associated with each store. Some of this information would be displayed in the “Activity” list view and some won’t. Since I don’t have any experience with SQLite, I’m not sure what the performance cost would be over storing the information in memory.
• There will be about a dozen or so methods that the service will need to encapsulate. For instance: once I get the store list, I may want to call the API again to find out if the store is currently open. Some of the information passed will be custom classes and therefore would require “Parceable” class definitions if I have to use IPC’s as part of my solution (if I understand the Android documentation correctly).
• I would also like to “Lazy-load” the list into my “Activity” so that I don’t have to wait for the full list before updating the user interface.
Possible Solutions (this is all guessing, so please don’t crucify me… that’s why I’m asking the question):
I could use a class extended from “Service.” It would have to handle the threading itself so that long internet calls via the RESTful API wouldn’t hang the system. Alternatively, I could do the thread manipulation first and call the API with the assumption that I can take as much time as I want. I think I would need to implement communication between the “Activities” and the service via IPC’s. This seems a little complicated to me. I’m not sure if I can use the “Messenger” class. It looks easier than the AIDL stuff.
I think I could use an “IntentService”. This would automatically create a separate thread and queue messages/tasks. I think I could communicate with the service (to get the lists of stores for instance) by “Binding” to the service. The problem I see is passing data back and forth and I’m not sure how I would cache the data between calls to the API since the service terminates after making the API call.
Anyway, I’d rather learn from someone who has already done this type of app instead of doing it the wrong way and coding it twice.
Thanks for the help.
AbstractThreadedSyncAdapter was made just for stuff like this. There's a fairly comprehensive (but complex example) here. Also, one of my favorite Google IO videos gives a pretty good overview of how to use it.
Your scenario is almost exactly the same as ours in my previous project. Here's what we came up with (I'm sure it's not original, but is patterned from one of those google io videos too)
A Service handles the request-response of RESTful calls to the server. This is triggered by the activity calling startService(Intent) that includes the parameters in a Bundle included in the intent. The Bundle contains information as to what API will be called, and what parameters are included.
The Service doesn't directly pass the result to the activity - instead it writes the result to an sqlite database. The activity will know that the transaction is finished by observing the db (via ContentObserver). Similarly, the Service can notify the activity once a transaction is completed via broadcast; the activity can catch this by registering a BroadcastReceiver - however the resulting data should still not be directly passed to the activity via Bundle, as there may be cases where the data is too large for the Bundle to contain (there's a limit for the length of a String that can be included in a Bundle) - you still want to put the result in the Provider. The activity should query for the data as soon as the Service notifies the activity that the result is there.
Additionally, you can include a "success" or "fail" flag in the Broadcast that the Service will throw for the Activity, so it will know if it still needs to query for result - this removes an additional overhead for failed transactions.
If you need to ask, No we didn't use AIDL for this architecture (but we did use it on another module that does facebook/ym chat over xmpp).
The "lazy-loading" I think can be asked in a different question, as it is an entirely different process.

Isn't it too complex to make REST call based on Google I/O Android REST client applications suggested

Based on Google I/O video, http://www.google.com/events/io/2010/sessions/developing-RESTful-android-apps.html, I got this question...
No matter the call is rest calls or normal http calls, they will have same issue mentioned in this video. So that means it is not good implementation if we use asynctask from activity.
Isn't it too complex to always implement Service and content provider even we just need to make a simple http call to a server and get a bunch of text to display on android?
This really confuse me, what do you guys think?
yeah its a lot of work for a one-off service call. Lately I have been using the new loader api for this type of thing. More specifically the AsyncLoader

Implementing asynchronous http requests on Android with AsyncTask

I'm building this client for a web service.
Pretty much everything makes requests to a server and now what I do is, I open a new thread and put all my requests in the same thread. That means I'm making all my requests in a serial way inside the thread and that turns into a lot of waiting for the user. Aiming to make the application faster, I want to make every server request in an asynchronous way.
I have a Networking class that handles all the HTTP requests I need and I'm thinking of making it so that every request starts its own thread.
I'm thinking of using ASyncTask for this but I noticed that with ASyncTask I'd need a class for each of my http requests (a class for GET, POST, PUT, etc). Is that the best way of doing it? is there a more efficient/clean way of doing this? What do you guys suggest.
Seems like a design decision that will depend on exactly what you are up to. There are various ways in Android to execute tasks depending on whether the user is waiting for some data or is being notified later on once the background task completes.
I would suggest you to look at this post that compares various task mechanisms in Android. Apart from this also go through the java.util.concurrent package.
I'm sorry this is not a concrete answer, but take it from me - it mostly depends on how are you trying to serve the user. So one can only suggest ideas. Hope this helps.

Categories

Resources