Long operations on Activity's onCreate() - android

I have an Activity that retrieves information from a remote server and displays it in a TableLayout.
The function that retrieves the information from the server has its own timeout, and exception is thrown when the timeout gets exceeded.
Now, when the activity is loaded, I want the function to be fired, and a progressDialog to be shown while the function works, and to be hided if the function is done working, or if a timeout exception was thrown.
The problem: I've put the code that do all the functionality described above in the onCreate() function. Nothing is shown on the emulator screen, since the onCreate() function hasn't finished running...
I've also tried to put the code in the onStart() function... same unwanted results...
I'm trying to avoid using of threads, because the functionality needs many variables that the thread will not has access to them...
How can i implement the wanted behavior??
Thanks.

Use AsyncTask with ProgressDialog bounded:
http://it-projects.spb.ru/?p=150&lang=en

Create a class implementing Runnable and put all your load logic in there. Call a function in the activity when finished (lets say onFinished(params...))
Create a UI Handler and get the handler to update UI in onFinished(params...)
Create a thread in onCreate and start it there to call your Runnable.

Related

Does OnResume() in Android makes Activity loading faster?

I was developing an Android Application where I have to load a large data from Android Database and view it on screen.
In earlier stages of development I used to retrieve data from DB in OnCreate() method and it really slowed the start of activity when data became huge. So I called the retrieving of data and viewing it on screen in OnResume() method, so that my app does not crash while taking too long to load it.
I know activity is not shown until OnResume is completed.
So is it a good approach to call time taking operations in OnResume instead of having all initialization in OnCreate() method?
So is it a good approach to call time taking operations in OnResume instead of having all initialization in OnCreate() method?
no - you should not do it inside OnCreate or OnResume. You should always do it inside working thread - like AsyncTask.
Any opertion that takes to long to finish, if executed on UI thread will block message queue - this means there are no repaint of UI widgets, user cannot tap on your app to do anything. Everything is blocked until your operation finished. After ~5s Android generates ANR (application is not responding) and kills your app.
You should never do IO operations on the main thread. This includes onCreate and onResume methods, which will always be called on the main thread.
To correctly load data you should either use an AsyncTask or the ContentLoader with its callbacks.
Generally speaking, to use a database with your application you should use a ContentProvider and CursorLoaders. There are plenty of tutorials on how to use these and it makes your code better manageable.

where should I do Download my data in android

I want to download the data from the web service, actually at the first time I just download it by the asynctask (background thread)and I execute it in the Oncreate method, this work fine.
but I also try to download in the ui thread in the oncreate method, so I just call the Httpclient directly in the oncreat method and this work fine and also faster,and the application doesn't fail when I press on the screen when it download the data.
I think the second method work fine because the application will not show the user interface until it finish the oncreate method.
Is this correct ? should I use the second method ?
the first method :
oncreate(bundle saveinstance){
new Task.execute("url");
}
second method:
oncreate (bundle saveinstance){
makehttprequest("url")
}
THANK YOU VERY MUCH
No, you should not use the second method. On newer versions of Android doing any network processing in the UI thread will cause an exception to be thrown. Given the indeterminate amount of time a network call can take, doing those calls on the UI thread makes for a non-responsive UI that will open up to a blank screen for as long as it takes to complete the call. Use the Async task and dhow a progress bar or a splash screen indicating to the user that you are downloading some content.

Using result of a thread in OnResume()

My Problem: Is it possible to prevent an activity to call OnResume() when it is being created? As I saw after the OnCreate() and onStart() method runs, the next one is the onResume(), although I only want to have it when I resume the activity from the paused state.
Why do I need this: I launch my activity (FragmentActivity, so lets say OnPostResume() ) starting with a thread which takes about 2-3s to be ready getting data from an external database. After the thread is done, I call a method which needs these data and I want to call it everytime that activity gets visible. The thread runs only when the FragmentActivity is created (onCreate()), and I cannot put the method into the onResume() because onResume() would be running way before the thread would finish its task. So it would receive not-ready data.
Anyone has a better idea?
Not sure of the exact application of this but I'll make a suggestion.
If you use an AsyncTask, you can send it off to get the data you need and in the onPostExcecute() method you can call your method that requires the data or update the view as needed. (It runs on the UI thread)
If you happen to already have the data you need in certain scenarios you could also bypass the AsyncTask and directly update the view.
This AsyncTask can be triggered in the onResume() method.
If I'm missing something, please let me know and I can adjust my suggestion.
I didn't understand the purpose of this, but here's a possible solution:
If you only wish to get the even of onResume on states that didn't have the onCreate before, just use a flag.
In the onCreate, set it to true, in the onResume check the flag (and also set it to false). if it was true, it means the onCreate was called before.
I personally would prefer to check if the result available, rather than always executing the getter-code in onResume. If the user somehow resumes your activity before the background thread is finished, you'd have a call on onResume, but don't want to display a result.
Maybe it would be a good idea to calculate/fetch the values in the thread, and let the thread return immediately (and cause the values to get filled in) if the values are already cached somewhere. That way you'd only have one entry point (the thread) for updating your UI instead of two (the thread and the onResume method).

My app's UI hanged

I am writing an android app, in which I have 1 button and 1 progress bar as UI elements.
The main aim of this app is when user presses this button, it has to create a database which contains all phone book contacts in customized format, means I am reading Contacts database and manipulating for my requirement.
So I am using SQLiteOpenHelper for database operations. I written a method downloadPhonebook() to perform all required operations. I written app such that when user presses button I am making progress bar visible and calling this method.
In this case, UI was hanged after clicking button and showing a dialog with Force Close and Wait buttons, after 15 seconds.
To avoid this I tried following mechanisms.
-> Broadcast Button click message and call method downloadPhonebook(). Here no use, same problem occurred.
-> Used a Thread and AsyncTask to call this method, here I got Runtime exceptions like Couldn't create Handler inside a Thread, Looper.prepare not called. I tried calling Looper.prepare() and Looper.loop() even exceptions occurred.
-> I tried with Android Service and Broadcast intent, again same problem UI hanged.
If anybody faced this problem or knows the solution or knows how to use Looper.prepare and Looper.loop please reply me. Thanks.
the workflow should be something like this: create a handler in your main class, add a handler in your sql helper class, pass the handler from the main class to the sql helper class when you create it. Run the download on separate thread from your main class, when download is ready, call yourHandler.sendEmptyMessage(0). You should override the Handler.handleMessage (I'm not sure about the exact name of the method) in your main class. You can also send messages to update the progress, read about Andoid Handler for more information

Calling asynctask from runnable

Is it possible to execute an AsyncTask from Runnable? in my experience it can be done, but not safely. When my app first runs my AsyncTask runs fine from the Runnable. But when the app is moved to the background, then brought back forward I get "Can't create handler inside thread that has not called Looper.prepare()".
Here's what I'm trying to do:
I'm using MapView and invoking runOnFirstFix(Runnable) within onCreate. My Runnable calls an AsyncTask to perform a web service call which returns some data based on the location.
I move the app to the background (by tapping the home button), after some time I bring my app forward again and I'm getting the exception at the point where I'm invoking execute() on my AsyncTask.
First of all, why is runOnFirstFix being executed again? Secondly, why is it causing the exception the second time around?
I'm guessing that there is some part of the lifecycle that I don't understand.
Thanks.
It wasn't initially obvious to me that the AsyncTask needed to be called from the UI thread. So when runOnFirstFix ran the second time it was from withing a Runnable which wasn't on the UI thread. To solve the problem I simple created another Runnable inside the first to run the AsynchTask.
And the reason my runOnFirstFix seemed to be called twice was simply because I was creating a new instance of it.

Categories

Resources