I'm developing an app in which I pretend to invoke a REST service for typical CRUD operations. Since I want to separate the requests processing from the UI thread, I'm planning to use an AsyncTask to do the separate work. However, my question here is: how should I desing my AsyncTask(s) model? Should I use one AsyncTask for all CRUD operations (is this even feasible?), or use i.e. 4 AsyncTasks (create, delete, update, retrieve)?
Thanks in advance
I would go with a ContentProvider instead of using AsyncTask.
According to this thread:
https://groups.google.com/forum/?fromgroups#!topic/android-developers/8M0RTFfO7-M%5B1-25%5D
on Android 4 AsyncTasks will be sequential.
So, for that reason alone your solution may be less than optimal.
But, ContentProvider just makes more sense for what you are trying to do, as what happens behind the CRUD calls the user doesn't care. You may want to run this on a separate thread though, as being on the UI thread for too long is bad.
It is really up to you, and perhaps, the REST service which you are consuming.
Some things to consider:
Is the service general enough that it would be easy to do everything in a with a single AsyncTask?
Will your code be easier to read and understand if you do things with a single AsyncTask? I would tend to think that it would be easier to read if you did one AsyncTask for each operation. (ie, CreateTask, UpdateTask...)
Will I get the reusability that I am after with my choice (whatever it is)?
Personally, I would create 4 distinct AsyncTask's, and any reusable code I might put in a base class, but again, it is really up to you for what is going to work best for you.
Personally, I use the Loader framework, available with the compatibility library. I have a subclass of AsyncTaskLoader for each of the CRUD operations, and it works really well!
I guess if you prefer to avoid having lots of classes you could use the same task (i.e. the create and update could technically fit in the same task) - when you subclass your AsyncTaskLoader create a setParameters(...) method which you can call when you create the loader in onCreateLoader().
It might help to read the above after you've reviewed the Loader documentation.
Related
I have an Android app made using Flutter.
Currently, most of the business logic runs on Android native Kotlin, but I love Dart so I am considering moving a lot of the logic to Flutter.
Is there any concern about converting Kotlin's coroutines to Dart's isolate?
There are no general concerns that I'm aware of. Although there are some points that you need to consider before doing the change.
The concurrency paradigm changes from multithread to single thread. This means that you should not think of changing coroutines to isolates, since you will not be using isolates so often or for the same purposes as coroutines.
Isolates are used for "extreme/unique" cases, if you want to perform a long running operation, you normally shouldn't opt out for an isolate, you should perform that with the simple async/await.
It's simpler to use async/await since you don't have to worry about resource allocations or race conditions, but at the same time it allows you to do "dirtier" things, to the responsability is on you.
Last thought on Isolates: they are a separate process so communication between isolates is only done through messages, so basic data should be passed between them and that could give you some headaches if you want to return some big data. (Of course everything is possible with serialization)
Hope this helps you to choose, if not, feel free to comment and we can discuss this further.
If I want to make a request from an Android device to a remote service, I can use AsyncTask, AsyncTaskLoader, Intent, etc to make the a request apart from the UI thread. It seems there are a lot of options, but I am confused how to choose among them. Could you explain when and which to use? Also, are there any other options besides the ones I have mentioned?
This is an extensively discussed question, since Android provides a long list of mechanisms capable to handle service calls asynchronously, besides the one you mentioned there's also:
IntentService
Native Threads
Now, the key point in your question is "When to use it" and here would be my answer:
In software the only golden rigid rule is the "It depends rule", there's no hard rules for anything in software development there's always different ways to approach a problem in software (i guess that's the reason of the word "soft" in it...) and that's exactly why it always depends, it depends on whatever you need and although one approach might be the most common way to do it like for example "AsyncTask" it doesn't mean at all that AsyncTaks is always the way to go, it always depends on the factors and needs that affect your functionality. There's plenty of things that nowdays get executed using AsyncTaks when maybe all you need could be just a regular common Native Thread.
The only way to be able to make a decision towards the most appropiate approach would be knowing ALL the features around a tool, like for example most people 90% of the time use AsyncTaks just to run doInbackGround on separate thread, but might not even need preExecute, publishProgress, postExecute, etc, and that's something a Regular Thread could do, just like this example there's features for every single object provided in order to do remote calls, however as i already mentioned several times, it all depends on what you need and what tool fits better your needs. Remember there's no hard coded rules for "How, When, and What" to use in software, IT ALL DEPENDS, and making good decisions in that "DEPENDS" makes the difference between good developers from excellent developers...
This is a list of things i usually take on count to implement either one way or another, this list do not apply for all the scenarios but might give you an idea.
AsyncTaks- I know is a good idea to make use of asynctaks when the functionality needs to be monitored, by monitored i mean, i need to keep track of progress during my job, like (download/task progress), because that's exactly what the AsyncTask was originally created for, it was created attached to "The Task Pattern", and if i don't need to make use of at least two methods for monitoring provided by AsyncTaks like onPreExecute,onProgressUpdate, onCancelled etc. I know there might be another way to implement it.
Native Java Threads - I know is good to make use of this tool when my task is not related to any view in android at all, and do not need to be monitored (example: removing/adding data from remote database, and the response might affect just persistence elements that will not be displayed like configuration preferences)
IntentService - When i want to do a one time task in a queueprocessor fashion way, but unliked a native thread, here i would like to have some application context in order to maybe bind an activity etc...
Regards!
Are there any advantages of Loaders over Async task? Also, how to make loaders compatible for phones with Android froyo.
Edit:
The primary problem here is that I'm not using the native DB(SqlLite). Using the DB on development server. Obviously, I can't use CursorLoader any more. AsyncTaskLoader has no examples at all. If any, please do link.
Is it a better idea to load the data required onto the local DB and then query it using CursorLoader?
Yes, Loaders are more advantageous than AsyncTask as they take care of a lot of things that AsyncTask falls short of, miserably.
Screen Orientation changes are difficult in AsyncTask. I used to have such a problem, till I used an Activity Control class, which I used to retain while configuration changed. I can give you some code if you want to know how. The app used to crash, though, when you changed the orientation multiples times even before the entire data loaded. The secret here is not load a lot of data with your first thread and and finish your threading tasks as soon as possible. Even if it happens in the background, Android has a shabby way of dealing with threads. You never know when one of your tasks would be killed.
Even if you use a AsyncTaskLoader, makes sure that you use an Activity manager. This will help you in getting more control over the activites and AsyncTask.
Yes, it is compatible in all the old version of Android. You need to include the support library(Most of the times, this is included by default but its always nice to double check.)
For one, loaders are easier to code (they're almost built-in in Fragments).
Loaders (specifically CursorLoader) also handles your cursor for you (like the deprecated manageQuery).
Check out this link to read on how to use Loaders pre-Honeycomb.
There simpler to implement and take care of a lot of the life cycle management which previously had to be done "by hand" with AsyncTasks. See the answer to this question for further detail.
With regards to using them with Froyo, they're available via the compatibility library.
It seems no one is talking about the disadvantages of loaders! I'm currently working on a system that runs other services in the background.
What I have noticed is that as soon as a screen with a loader is resumed. The cursor used by the loader locks up the DB.
It may not be open to most people but getDatabaseWriter from sqlite is actually a synchronized method and hence the cursor used by the loader is never closed until the loader is reset or terminated thus locking up access to the DB.
I cannot recommend using a loader under these circumstances nor can I advice using a loader when your result set consists of less than 100 items which are static and never seem to change.
Another advantage with loaders is that they handle screen turn event gracefully whereas asynctask can give you trouble.
Biggest diff:
CursorLoader will update your UI's content as soon as its related ContentProvider changes its content(say through a Service), while AsyncTask will only update your UI when you tell it.
writing a small android game for a university assignment and just wanted to check what I'm doing is correct.
I'm creating a Mastermind type game and am unsure how to handle basic game operations such as checking if a guess is correct.
Am I correct in thinking that the best way to handle these operations is to create inner classes that extend Async to avoid UI lockup?
If not could anyone suggest any other ways?
Cheers!
After many weeks of developing my application, AsyncTask is what I used instead of standard threads. AyncTasks are less likely to get killed, they create a worker thread and handlers by themselves so you can update GUI through it more easily than standard threads. But remember that only one instance of AsyncTask can work at a time.
I don't think you need AsyncTask for this game at all. AsyncTask is a process for which you do not know how long it will take and you don't want to block your UI thread, like downloading something from Internet.
Your game can be completly events driven. Whenever the user makes a move you call your methods.
If you want to have animations while the user thinks then SurfaceView can do the job.
I've found a sample to download a large data file at the following link,
http://code.google.com/p/apps-for-android/source/browse/#svn/trunk/Samples/Downloader
It seems to be pretty nice (I haven't yet tested it). But I also have read some posts at the stackoverflow to do the same thing by using the AsyncTask class, not using the Thread class as the above sample.
What I want to know is, which should I use to achieve downloading a file? And if AsyncTask is better, would you point me to a sample code?
Disclaimer: i am not Android developer, answer comes from general experience.
Thread class is most suitable for long-running activities, not for asynchronous tasks. Except if you manage pool of workers, but still lifetime of thread is same or nearly same as application. Consider that creation of thread is expensive operation.
AsyncTasks and other helpers are usually for some single activities that you want to do in background so not to block the app. They are usually well managed by the platform and are cheap.
My opinion: use AsyncTask if you want to load pages occasionally. If your app will load pages all the time in the background consider thread.
For understanding what has to be used one must understand the nature of the task we are about to perform.
Suppose we are going to download large file.... would you being a user want to see it or rather let it run in the background?? i guess i dont mind running that task in the background(unless it is game and some graphics are being downloaded).
Taking this thought in mind, if we use the Asyntask, the user must have to keep the App open until the download operation has been completed; as three out of four methods of AsyncTask runs on the UI thread. (check out the link : https://developer.android.com/reference/android/os/AsyncTask)
In the other case where we are using the AsyncTask to download graphics file for a game, it would be completely fine to go for it.
So I believe it is better to go for Thread or even better to go for Service to download the content so that one may continue to work further on the app/ close the app or even run some other app.
These two options have an equal probability of being killed while download is in progress (when user switches to another app). Still, AsyncTask is less mess. For downloading large files, consider using a Service.
AsyncTasks in Android versions prior to 3.0 uses a pool of threads in background to execute the tasks, but in versions after 3.0, a single thread is used to execute the AsyncTasks.
If you need to make a lot of requests at the same time and your Android version is higher than 3.0, use a pool of threads, but if you only have to make a single download (not mind the Android version), use AsyncTask, it will be executed at a single background thread without problems, easier than manage a Thread by your own.