Android: Run function after Activity is created - android

Currently, my app starts with a menu. Once a menu item is clicked, it starts a Activity which grabs content from an online API.
The problem I am having is, once the menu item is clicked, the application waits until the http request and response is complete before it displays the activity.
My Question is, How can I have the Activity display instantly with the layout and static View. Then once the activity is loaded, then I start fetching data from an API?

Why run after when you can run concurrently!!
Use an AsyncTask in your onCreate()/onResume() method.
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(...);
AsyncTask task = new MyTask();
task.execute(/* optional params */);
}
In your implementation of MyTask, put your long running code (the data fetched from the http request) into the doInBackground() method. Once the doInBackground() method returns, you can update your View in onPostExecute().
Also, take a look at Painless Threading, as there is lots of helpful android threading information in there.

You may use either an AsyncTask during the onCreate method to fetch your results and update your activity Asynchronously. Additionally, I think you may use a separate thread to do the same functionality. Pretty common use case. Here's the relevant Android docs.

Related

Get data from more than one AsyncTask in one class?

My situation is this:
first I call first AsyncTask which fetched required Items from database. After that, I call another AsyncTask, which fetches these Item images.
I am getting data from AsynTasks by using callback.
Here is the issue - since I am using callback, in my class I have method processFinish which returns AsyncTask data when it finishes its computation. The problem is with two Async tasks which depend on each other. What should I do now?
You can use the get() method of asyncTask that will wait for the output and wont proceed further
also you can use it with a timeout.
ex new BackgroundTask().execute.get();
or
new BackgroundTask.execute.get(long timeout);
You could execute one AsyncTask inside another, but you should do it inside onPostExecute() because this method runs on the UI thread.
#Override
protected void onPostExecute(Void args) {
new AsyncTask2.execute(..); // Start second task once you've got first results
}
And you call your method processFinish(..) only once, after the second AsyncTask is completed.
Anyway, is there a reason why you use two AsyncTasks ? With your explanations we could believe that you might be able to use only one task.

Asynchronously load data in android

what is meant by asynchronously loading data in activity or fragment in android?
This is my question. I searched everywhere. I'm not getting a generalized definition for this?. I can't get the term mentioned in android developer also.
Can anyone provide me the basic explanation of this term?
Asynchronous in Android mean that you do stuff while the user can interact with the User Interface (UI) : you are not blocking the UI while you are doing long stuff. So the user can still navigate, change activities or fragment and your data is still loading.
For data : you load it, parse it and do whatever you want in a NON-UI Thread (using AsyncTask eg) and then notify the UI, and display what you need to.
You have many possibilities to implement Asynchronous load in Android, and you have many different way to manage your request. I personnaly recommend using Retrofit if you need to use a Web API.
It means that you load your data in a separate thread than the UI thread. You launch your HTTP request for example in another thread and when it finished you notify the UI thread to refresh display.
This mean to load data in separate thread rather than load the data in main thread.Loading data in main thread may cause app to block
The AsyncTask class encapsulates the creation of a background process and the synchronization with the main thread. It also supports reporting progress of the running tasks.
To use AsyncTask you must subclass it. AsyncTask uses generics and varargs. The parameters are the following AsyncTask .
An AsyncTask is started via the execute() method.
The execute() method calls the doInBackground() and the onPostExecute() method.
TypeOfVarArgParams is passed into the doInBackground() method as input, ProgressValue is used for progress information and ResultValue must be returned from doInBackground() method and is passed to onPostExecute() as a parameter.
The doInBackground() method contains the coding instruction which should be performed in a background thread. This method runs automatically in a separate Thread.
The onPostExecute() method synchronizes itself again with the user interface thread and allows it to be updated. This method is called by the framework once the doInBackground() method finishes.

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.

Several simultaneous AsyncTasks from different Activities - how to catch proper response?

I have several Activities and each of them has its own AsyncTask which sends requests to a server and catches its responses. These days if AsyncTask is in execution I have a ProgressDialog which blocks User from navigation to another Activities. I want to get rid of the ProgressDialog and substitute it with ProgressBar view so user can switch between Activities. My concern is about the following: what if AsyncTaskFirst started in ActivityFirst and user navigates to ActivitySecond where AsyncTaskSecond is starting also, couldn't it happen the response from the first request will take ground in ActivitySecond so I'll miss it in ActivityFirst? If it is impossible, that's fine. If it is - how to handle such a case? Thank you very much in advance.
If the AsyncTask begun execution in the first Activity then it's execution of the postExecute method should be expected to affect the first Activity and not the second unless you've explicitly set it up otherwise.
I assume your AsyncTask has some kind of reference to the Activity, so it can update the progress bar.
If this is so, then all you have to do is add a method in the AsyncTask:
public void setHandler(MyTaskHandler handler) {
this.handler = handler;
}
When you start a new activity, call this method and pass on the new activity.
Then when the AsyncTask calls the Activity's update progress method, it will use the current Activity regardless of where the task was started from.
BTW: It might be better to use fragments and not activities, if it's the same component only different parts of the display. Then you do not have this problem at all, because the activity remains the same. See these guides about fragments:
http://developer.android.com/training/basics/fragments/index.html
http://developer.android.com/guide/components/fragments.html

Asynchronous update Android context menu

Word up, I need to update a context menu for a widget (listview in this case).
The items for the menu need to come from a call to a web service. If the web service call is made synchronously on the main UI thread then this works.
However due to fact that I'm calling a web service it needs to been done asynchronously via an AsyncTask or similar to avoid ANRs etc. This asynchronous update of the menu via menu.add() within the onCreateContextMenu doesn't work, i.e. asynchronous calls to menu.add() don't result in the context menu being displayed. Also note the async menu updates are done on the UI thread via the onPostExecute of an AsyncTask.
All Ui updates have to be done on UI thread. So you will have to post a runnable onto Ui thread.
Something like
runOnUiThread(new Runnable() {
public void run() {
//DO UI update here
}
});
Or you will have to call publishprogress() in doinBackground function of Asynctask and then do Ui work on onProgressUpdate().
If the Ui update can wait you should do it in OnPostExecute
Thanks to those that have provided answers, I may have to leave this for now with a somewhat half baked solution. For those reading this that are experiencing the same problem, my current solution uses the openContextMenu(View view) method in the activity to call back to the onCreateContextMenu. A simple boolean state flag determines whether to do the async call or populate the menu with the data from a previous async call. This design feels a bit awkward and fragile to me but works.
Save the information, you get from the web-service in the activity. Then in onPrepareContextMenu() use this information to update the menu. onPrepareContextMenu() is called before the context menu is displayed. OnCreateContentMenu() is only called once for every activity instance.

Categories

Resources