Context : networking(http request and response).
My question has two parts - one about volley and one about AsyncTask.
I'm learning to implement httpConnection using volley and AsyncTask, so please bear with me.
My question is, in what order the callbacks are called, after getting response from network? (In the case of volley and AsyncTask)
Are callbacks executed sequentially?
Consider this scenario,
I have 2 AsyncTasks. After getting response form network at same time, in what order callback will be called in postExecute()? Will both callbacks to UI thread will occur simultaneously as 2 Asynctasks are in seperate threads? or will they be executed sequentially?
I have read these SO posts,
can-i-do-a-synchronous-request-with-volley
multiple-asynctasks-onpostexecute-order
running-multiple-asynctasks-at-the-same-time-not-possible
how-to-manage-multiple-async-tasks-efficiently-in-android
how-to-synchronize-two-async-task
Thanks
Edit :
Consider this code of AsyncTask implementation,
public class AsyncTaskImplementation extends AsyncTask<String, Void, String> {
private final interface appAsyncTaskInterface;
public interface responseInterface {
void onSuccessHttpResponse(String resultJsonObject);
void onFailedHttpResponse(String failedMessage);
}
public AsyncTaskImplementation(){
//initialise
}
#Override
protected String doInBackground(String... params) {
//executeHttpRequest and return
}
#Override
protected void onPreExecute() {
//pre execute stuff like connection checking
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null&& !result.equals("")) {
responseInterface.onSuccessResponse(result);
} else {
responseInterface.onFailedinterface("failed");
}
}
}
Question wrt to above code :
Consider two AsyncTaskImplementation objects, A and B created in a UI thread.
Now A and B will execute a http request (assume the code is implemented).
After that they will return response through interface responseInterface.
So my question is regarding this. Will A and B simultaneously invoke callback methods in UI thread through responseInterface?
Should I use synchronized to make sure that callbacks are synchronized? Or AsyncTask ensures that callbacks are invoked sequentially?
Related
I need to perform a very simple operation that involve network. I know that this must be done with an Async Task, because run a task that involves Network operations on main thread is bad.
Since is pretty verbose using the classic way
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
//to do
return "Executed";
}
#Override
protected void onPostExecute(String result) {
//to do
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
for a method static method invocation that must download only few bits
I'm wondering if there is some more concise form or alternative that I could use.
You don't need an AsyncTask. It is just a convenience to use because it already has callback methods.
You can create a new Thread and execute your network call there.
There are many ways to create a worker thread. It depends on what are you doing with network.
If you just want to do simple network operations such as download some JSON data then get it back to update UI: use AsyncTask.
If you want to do long network operations which involve moderate to large amounts of data (either uploading or downloading): use Thread.
If you want to continuously send/receive message to/from the Internet, use HandlerThread.
So in conclusion: AsyncTask is already the simplest and easiest to use. Beside, you don't need to override all methods, just override doInBackGround() and onPostExecute() if you want to receive data.
See: Asynctask vs Thread in android
You can always use AsyncTask.execute(() -> { /* network operations */ });, the downside is you don't get any of the callbacks so I tend to only use this when prototyping or with very simple tasks.
Use an anonymous class inside a method:
public void asyncOperation () {
new AsyncTask<Task, Void, Boolean>() {
#Override
protected Boolean doInBackground(String... params) {
// Your background operation, network, database, etc
return true;
}
}.execute();
}
Here is my code:
new Loading.LoadTast(ctx) {
#Override
protected String doInBackground(Integer... params) {
Looper.prepare();
String msg=changePwd();
closeProgressDialog();
if(msg == null) {
SmartNgApplication.getInstance().exit();
} else {
BaseHelper.showToast(ctx, msg);
}
Looper.loop();
return null;
}
}.execute();
public abstract static class LoadTast extends AsyncTask<Integer, Integer, String> {
private ProgressDialog progressDialog;
private Context ctx;
public LoadTast(Context ctx) {
this.ctx=ctx;
}
protected abstract String doInBackground(Integer... params);
public void onPreExecute() {
super.onPreExecute();
progressDialog=ProgressDialog.show(ctx, "", "loading...", true, false);
}
public void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
BaseHelper.showToast(ctx, result);
}
}
Click the button to run the method. Clicking it 5 times AsyncTask.onPreExecute is called but not call doInBackground so the screen still show a dialog.
I think have something wrong for AsyncTask THREAD_POOL_EXECUTOR
You should not call any UI changing methods in doInBackground. Thats what onPostExecute is there for. Do only whats not allowed on the UI thread in doInBackground.
To check why doInBackground is not called, please try putting the implementation (from the anonymous inner class) into LoadTast just too see if it is called then.
I have implemented an AsyncWrapper by having subclasses call renamed onPostExecute and doInBackground. It should be possible to overwrite the wrapped Methods in an anonymous inner class like the one you are using in your example.
This is the short version. My real code involves some genral exception handling not only the call to the wrapped methods.
public abstract class AsyncTaskWrapper<Params, Progress, Result>
extends AsyncTask<Params, Progress, Result> {
#Override
final protected Result doInBackground(Params... params) {
return wrappedDoInBackground(params);
}
protected abstract Result wrappedDoInBackground(Params... params);
protected abstract void wrappedOnPostExecute(Result result);
final protected void onPostExecute(Result result) {
wrappedOnPostExecute(result);
}
}
As Todd Sjolander said in this thread ...
The multi-threading model changed between 2.3.5 and 4.0.4. AsyncTask
now defaults to having all subclasses in an application using the same
thread (i.e. only one AsyncTask can run at a time!). It's explained
here:
When first introduced, AsyncTasks were executed serially on a single
background thread. Starting with DONUT, this was changed to a pool of
threads allowing multiple tasks to operate in parallel. Starting with
HONEYCOMB, tasks are executed on a single thread to avoid common
application errors caused by parallel execution.
If you truly want parallel execution, you can invoke
executeOnExecutor(java.util.concurrent.Executor, Object[]) with
THREAD_POOL_EXECUTOR.
With that in mind, it could be that another AsyncTask is running in
your app, thereby preventing this one from ever starting. That would
explain why it works fine on your 2.3.5 device, but not your 4.0.4
tablet.
The goal:
Using Google App Engine server and Android client, I'm trying to put on the Google map at the Android client Users overlays. Every 30 seconds I'm polling the server and getting Vector that contains users and adding it to the map.
Current status:
I'm dong all that using in one new thread, So after running the app I got:
weird behaviors(delayed overlays, multiple overlays) and after that crushed with ConcurrentModificationException.
After reading a bit i figured out that I need to work with AsyncTask.
Correct me if I'm wrong,But I understand that everything done in the Activity at at onCreate is "running" in UIhread so I need to put the "Logic" (All the Network handling) in doInBackground and all the UI Handling like putting overlays on the map in onPostExecute.
My Question are:
1) In the current status I'm doing:
new Thread()
{
#Override
public void run()
{
super.run();
while(true)
{
SystemClock.sleep(30000);
Vector responseFromServer = getUsersVectorFromServer();
putNewOnlineUserOnTheMap();
}
}
}.start();
What is the right way to convert this To AsyncTask?
Do I poll the server still using new thread in the doInBackground or there is right way to do this?
2) Is there a specific list of what counts as UI to put in onPostExecute or any concepts list?
In my case I guess that in need to put putNewOnlineUserOnTheMap() in onPostExecute.
Thanks.
Something similar to the following:
class UpdateTask extends AsyncTask<Void, Vector, Void>{
#Override
protected Void doInBackground(Void... params) {
// this is running in a background thread.
while (!isCancelled()) {
SystemClock.sleep(30000);
Vector responseFromServer = getUsersVectorFromServer();
// send the result back to the UI thread
// onProgressUpdate will be called then
publishProgress(responseFromServer);
}
return null;
}
#Override
protected void onProgressUpdate(Vector... values) {
// this is executed on the UI thread where we can safely touch UI stuff
putNewOnlineUserOnTheMap(values[0]);
}
}
You can't use the result of the task since the task is finished then. But you can use the progress publishing mechanism to get periodic results. If you use it like that and do the modification on the UI thread you should not get ConcurrentModificationException because you do the modifications on the one thread that can safely modify the UI.
One thing to note here: create new instances of your Vector in the background thread and then use it to update the UI. But don't touch the same object afterwards in the backgroundthread. That way you don't need any synchronization since after the background thread sends it away it is only the UI thread that touches it. (and you could use a simple ArrayList instead of a Vector)
AsyncTask uses generics and varargs.The parameters that are passed to the asyntask are . TypeOfVariableArgumentsParameters is passed into the doInBackground(), ProgressParam is used for progress information and ResultParam must be returned from doInBackground() and is passed to onPostExecute() as parameter.
example:--
protected class ParsingTask extends AsyncTask> {
private ProgressDialog loadingDialog = new ProgressDialog(JsonParserActivity.this);
protected void onPreExecute() {
loadingDialog.setMessage("loading app store..");
loadingDialog.show();
}
#Override
protected ArrayList<Items> doInBackground( Context... params ) {
// do ur process here.
return result;
}
if (!this.isCancelled()) {
}
return result;
}
#Override
protected void onProgressUpdate(String... s) {
super.onProgressUpdate(s);
Toast.makeText(getApplicationContext(), s[0], Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute( ArrayList<Items> response ) {
//if u r dealing with list view and adapters set the adapter here at the onPostExecute()
loadingDialog.dismiss();
}
#Override
protected void onCancelled() {
super.onCancelled();
Toast.makeText(getApplicationContext(), "The operation was cancelled", 1).show();
}
}
You can use AsyncTask like below. Hope this will help you..
Class YourClass{
void YourClass(){
NetworkTask nT = new NetworkTasK();
nT.execute();
}
}
protected class NetworkTask extends AsyncTask<Void, String, Boolean>
{
#Override
protected Boolean doInBackground(Void... params)
{
try
{
String response;
while(keepreceiving)
{
response = in.readLine();//Prog Counter stops here until getting i/p.
if(response != null)
yourFunctionForResponse(response);
}
}
catch (Exception ex)
{
}
return null;
}
private void yourFunctionForResponse(String response){
//things to do....
}
}
You may also try runOnUiThread(Runnable action) along with this to implement your work.
I understand that http requests should be run as part of an AsyncTask to keep it off the the UI thread. But what about the case where multiple and sequential http requests may be necessary, where the latter http requests depend on the earlier, and therefore need to be run sequentially?
In this case, is it best to put the latter AsyncTasks in the onPostExecute of the earlier AsyncTasks, to make them run sequentially?
Or does this indicate that I have the wrong approach?
To make a lot of HTTPRequests in a queue, try this:
private class QueueExample extends AsyncTask<URL, InputStream, Long> {
protected Long doInBackground(URL... urls) {
SynchronousQueue<URL> queue = new SynchronousQueue<URL>();
for(URL url : urls){
queue.add(url);
}
for (URL url : queue) {
InputStream in = new BufferedInputStream(queue.take().openConnection().getInputStream());
publishProgress(in);
}
}
protected void onProgressUpdate(InputStream... progress) {
doSomethingWithStream(progress[0]);
//Do Something
}
protected void onPostExecute(Long result) {
//Finished
}
}
If you don't have to update the UI between requests, just execute them one after another in doInBackground() and accumulate the results. When done, just return and use the result in onPostExecute() to update the UI. If you do need to update the UI, you can call publishProgress when you get some intermediate result and update in onProgressUpdate().
I am using AsyncTask on button click to refresh the screen. Following is the sequence of events that happen on btn click
progress dialog shows up
The doInBackground is called and thread is initialized which calls a web service. The web service fetches/uploads data. A pass/fail flag is set once the web service is called.
My problem is the onPostExecute is never called and therefore the screen is never refreshed.
And secondly by the time the data is downloaded and the web service sets the flag my code has already hit return stmt in doInBackground.
Question is how do i stop execution in my asynctask so that the web service is done downloading/uploading the data and finally execute onPostexecute.
FYI
I also get the following warning in eclipse
The method onPostExecute(boolean) from
the type
Screen.ConnectWebService is
never used locally
private class ConnectWebService extends AsyncTask <Void, Void, Boolean>
{
private final ProgressDialog pd = new ProgressDialog(screen.this);
protected void onPreExecute() {
pd.show(Screen.this, "Sync", "Sync in progress",true,false);
}
protected Boolean doInBackground(Void... unused) {
if (SyncInProgress == false)
{
CallWSThread();//creates thread which calls web service
}
Log.d("doInBackground","doInBackground");
return SyncStatus;
}
protected Void onPostExecute(boolean result)
{
pd.dismiss();
if (result==true) drawRadioButtons();
return null;
}
}
It should be:
protected Void onPostExecute(Boolean result)
As djg noted, you have a typo in your method declaration. You can avoid these kinds of mistakes by using the annotation #Override when you're implementing methods from a super class.