I'm building a news reader for Android, where the first Activity will show a list of the latest news, combined with a thumbnail preview image.
In order to get the thumbnail I have to run a method, which increase heavily the loading time; so, I was thinking to create a separate thread to run everytime.
More specifically I'd like to load the news titles first, and then load the pictures, one by one; while doing all this I don't want the UI to be locked (for instance, if an user touches a news I want the app to load it, even if thare are some thumbnails still loading).
My question is: should I use handlers (one thread for each news) or AsyncTask (one asyncTask object for each news) to achieve this?
Thank you for your replies.
Handler Vs AsyncTask
I would use an asynctask to download all the "news links" and then have that asynctask call an asynctask to download each thumbnail and update the UI onPostExecute. Then, if the user clicks a link before it is done, you could call cancel on the main Asynctask, which would check for isCancelled() between each thumbnail asynctask and would return if it was cancelled.
No doubt that AsyncTasks are more simplified and modularized than the thread-handler architechture, but internally they perform the action in same way.Coming to your problem, I would suggest that load the news first.Your news pojo/class can be like containing two feilds, title and imageUrl.Now display the news list and start another AsyncTask that fetches the images one by one and store them in a Data Str/list.your adapter should be "notifyDataSetChanged()" every time the image is fetched from server.
This way you are allowing user to see the news first, and the images are loaded without making UI get blocked.
i wit make asynch task for loading the data and then excute a task thats populate the list when the async task is don ore while it is running
Related
In my activtiy, I am loading a recyclerview that downloads pictures from the internet.
The only problem is, that the acitvity will only become visible when the loading of the pictures is done. I call the function from within the OnCreate() method. Since this made it obvious, I decided to put the function into OnWindowFocusChanged(), yet still the activity will only start showing when the pictures are loaded. (This is like a 1 second delay, but its a litttle too much.)
Where would I call my InitRecView() method to make sure it will start loading once the activity is already visible to the user?
Thanks
You are getting this problem because you are loading images on main thread. It may also cause skipping layouts.
Here is the solution: Use Handler or Async task for download images, show progress till then and once image is downloaded then notify adapter using adapter.notifydatasetchanged().
note:make sure you write UI related code in runOnUiThread since you cannot handle UI elements in background task.
I'm working with an app that grabs a decent amount of data upon start each time since I need to immediately know things like location and weather fcst in the area.
In my mind I see a loading animation that smoothly moves around for 3 to 7 seconds while everything runs so there isn't just a blank screen or a static title image.
BUT:: I'm running into issues with getting animations or images to load before all of the data is searched for. And I only want the animation to run as long as data is loading. So I have the application switch to a new activity as soon as everything is loaded.
Is there a way to for the animation to run before things are done or do I need to somehow set everything up as an async task. And then how do I pass the async task to the next activity?
So I found an answer to my own question after reading some books. In short, the loading screen that i was looking for uses a splash screen with asynchronous tasks. Either AsyncTask directly or you can implement a service solution.
Extra: I noticed that if you run an async task which starts a GoogleAPIClient, onConnected executes on a pool thread or something, point being you can do UI work on the main thread again without wrapping back to AsyncTask.
I have a activity that show one listview. In the activity I have a one AsyncTask (named here of AsListView) to get values from internet and fill some informations in each item of the listview. Work fine.
Now I created a button in ActionBar to show one image from streetview. To do this I have implemented another AsyncTask (named here of AsImage) to get image from google and show in a DialogFragment, but is necessary wait the execution of all AsListView Threads. It spends long time depending of the number of items in the list.
To execute AsImage rapidily, I cancel all AsListView tasks, but it's not good for me (user loss informations). The ideal soluction is set AsListView tasks to wait while AsImage execute. When AsImage finish I set AsListView tasks to continue execution. But I know that is not possible handle the control of execution of AsynkTasks.....
Some solution?
You can try to synchronize the AsyncTasks using a CountDownLatch.
Otherwise if you want you can use Threads instead of AsyncTasks and set their priorities, but there is a reason android made the AsyncTask class so I recommend you use it.
I'm trying to solve this, right now I have a Details Page activity (which loads dinamically from the DB depending on the item that was selected from a ListView). Each Details page can have between 1 and 5 images, which are downloaded from an online server. The problem I have is that the activity is not showing until the pictures were downloaded.
Basically the activity won't show until onCreate finishes. I'm using a thread to download the image so the UI doesnt freeze, My question is, where could I download and set the ImageView to the downlaoded bitmap so the user will see the activity and information straight away after clicking on the list item and then download and set the image after downloaded?.
I tried putting the thread on the onResume but I think it doesnt help either. What would be the best way?
Regards,
George
You need to implement an AsyncTask. Which executes on a background thread and prevents blocking of the main thread. You simply create a class that extends AsyncTask like below
EDIT - Yes, this will display your Activity even before the images get downloaded. You simply call the execute() method of your AsyncTask in onCreate() Have a look at the page on AsyncTasks above for a complete overview. It's really simple to implement you just need to be aware of configuration changes if your AsyncTask has not completed.
You might also want to look into caching your bitmaps in memory to prevent them from being unnecessarily downloaded again.
public class DownloadItemDetails extends AsyncTask<String, Void, ArrayList<Bitmap>{
protected ArrayList<Bitmap> doInBackground(String...params){
//Download each Bitmap here, and add them to a list to be displayed later
}
protected void onPostExecute(ArrayList<Bitmap> results){
//This method executes on the main thread, so after your downloads finish
//You can set your imageviews in your Details Page here
}
}
According to your curiosity to make user happy, I think you have to use Android Universal Image Loader library from Github. This library provide you asynchronous image loading, caching and displaying.
You can also use ShutterBug - Remote Image Loader from Github for same. It also fetch remote images and cache them. It is particularly suited for displaying remote images in lists, grids, and maps.
My Android application is running very slow and lagging much. I have PHP API on my server and my application requests data through HTTP.
Though, the problem is that sometimes I should wait for few seconds before I can see the result. I have all calculations done in the main thread in onCreate (parsing XML, adding controls) and downloading data from HTTP server in AsyncTask.
How to optimize my program to make it faster? I want it to load activity first and only then, in background, download and parse data. How is it possible? Sorry for newbieship.
what did you mean by lagging ? Will you elaborate more on the issue.
One suggestion that remove parsing XML from OnCreate and move it to AsysnTask. The reason for this is as you are doing time consuming operation in UI Main thread which will impact the activity to be shown.
Create thread to perform HTTP related operations and parse the response on the same thread and while doing the parsing operation show dialog.
Dismiss the dialog when parsing got completed and then show the activity which you want to display.
In the doInBackground() method in AsyncTask add the data parsing and create the data objects then in onPostExecute update the ui elements.
The reason to do something like that is for the application to be responsive in all this time and just make small jobs on the ui thread so as not to freeze.
You can instatiate your views to a default state an add a progress somewhere on top to indicate that the activity is currently loading. For example you can create an empty ListView or a Button that cannot be selected and when the parsing is done then you should set the adapter to the list and make the button back to selectable again.
All this things can be implemented according to what you want the user to be able to do in the time of his waiting.