I am trying to create a lot of asynctask, and run one by on in order.
Is it possible? I can't find any solution for this.
onPostExecute and then call a new AsnycTask again is not a good solution for me.
SO what I want:
async1.execute
async2.execute
async3.execute
async1.over->async2.start
async2.over->async3.start
If you use the serial executor (default in API 11 and above), this happens automatically. If you need this to work before API 11, you need to do the classic wait/notify trick (https://www.science.uva.nl/ict/ossdocs/java/tutorial/java/threads/waitAndNotify.html)
Do like
async1.execute
then write async2.execute into onPostexecute of async1
and then write async3.execute into onPostexecute of async2
There is no any other valid way. You can think about to implement threads (wait/notify), but that is not for asyntask.
I guess you should use Executor whit BlockQueue instead of AsyncTask, and use Handler to send handle the result. BockQueue is a FIFO data structure, and fit your flavor...
// Async Task Class here async1
class YourAsynClass extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Shows Progress Bar Dialog and then call doInBackground method
showDialog(progress_bar_type);
}
#Override
protected String doInBackground(String... PassYourdata) {
// do your stuff here
}
#Override
protected void onPostExecute(String IFYouwantPassData) {
// Dismiss the dialog
dismissDialog(progress_bar_type);
// here async2
new SecondAsyncTask.execute(Passeddata);
}
}
and in the third one do the same
Let the first AsyncTask is MyAsyncTask1 and the second one is MyAsyncTask2. Now what you want is.
Execute the MyAsyncTask1 from with in the activity
Take the response received
Now on successfull response,execute the MyAsyncTask2
what about calling them in sequence like:
MyAsyncTask1.execute();
MyAsyncTask2.execute();
The problem with the above code can be understood by the fact that calling execute on the AsyncTask object will create a new thread to run in different memory space,and immediately the next AyncTask will be started with in its own memory space.But that was not what we want.We want that the first thread must finish its working and only then the second one will start to work.How this can be achieved?
The answer lies in the onPostExecute().This is the method which will help you to get rid of this situation.While you call execute on MyAsyncTask1 then after doInBackground() of the first AsyncTask its,onPostExecute() will be called .Place a check in that onPostExecute() that if response is null, if received response is not equal to null,and is a valid response then call execute on the MyAsyncTask2(with respective parameters if specified).
SEE THIS
You can do this in a chain.....
Related
I found this bug on with the following code:
(it.context.get() as? Activity)?.runOnUiThread(Runnable {
it.weakRefIOnDataRefreshed.get()?.onDataRefreshed(refreshedItemList)
})
The code above is inside a run method that runs in a non UI Thread. I want to call a method in fragment with the refreshedItemList as argument. I want to debug the onDataRefreshed method (which is inside a Fragment), and I'm putting inside this function a break point but nothing happens. I also put a Log method to make sure that the code is running and the Log method prints indeed. What may be the problem that the debugger doesn't stop on the line which I have marked?
In your class where that background thread works define a Handler object and use post method to update UI e.g. (Java).
// Define handler object
Handler handler = new Handler(Looper.getMainLooper);
...
...
// Here ise where you want to update your UI
handler.post(() -> {
// Your code with which you want to update the UI
}
I am using Google Drive API on an Android device.
I need to get the contents of a file on Google Drive to a string. Something simple like
String dbData = driveObject.downloadFileToString("db_export.txt");
I am implementing a "GoogleDrive" object. I need to do this without all the mess of tasks and threads and callbacks. However, I can't do it.
Here's an example: I have implemented a method called "findFileByPath" that returns the file ID of a file whose pathname is given as a parameter. However, the Android gods have forced any calls to this -- because it deals with network activity -- to happen in a thread or AsyncTask. The problem is that any pause to wait for the task to complete causes the Google Drive API threads to pause. So....if I do this:
FindFileWithAsyncTask ffwat = new FindFileWithAsyncTask();
ffwat.execute(filePath);
File f = ffwat.get(5, TimeUnits.SECONDS);
where the call to "findFileByPath" is done in a AsyncTask called "FindFileWithAsyncTask" it just hangs everything. The Google Drive API only proceeds when the "get" times out.
HELP! There has got to be a way to do this that can avoid -- or mask -- all the asynchronous BS.
Any clues? Thanks!
It's hard to get rid of AsyncTasks when using network services because otherwise your UI will freeze waiting for the result.
Try to do this:
new AsyncTask<String, Void, String>() {
#Override
protected String doInBackground(String... params) {
String dbData = driveObject.downloadFileToString("db_export.txt");
return dbData;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
File f = new File(s);
}
}.execute();
Then you will wait for the result on onPostExecute method.
And creating the AsyncTask on the fly will reduce the boring code.
So, I want to display an image in an ImageView that is downloaded from a website and saved on the device's file system. The downloading of the image is done by calling a method in another class (in one of my separate library projects). This method, in turn, calls an AsyncTask to do the downloading in another thread. On the post execute of this AsyncTask, I want to set the image for the ImageView. Keep in mind that this separate library is independent of my main app and knows nothing about my UI (and I wish to keep it this way).
I have a method in the UI portion of my code (in a fragment) that sets the image for this ImageView. I'm thinking it would be nice to pass this method to the library method that retrieves the image. That way, when the download is complete, onPostExecute() could call this UI method that I have. The dilemma I'm facing is I don't want any compile-time dependencies for my library that references my UI/ImageView.
Finally, not every time when this AsyncTask is called do I want to do anything in the post execute. In other words, any post execute logic is completely optional.
General Flow:
1) Code in my fragment calls MyLib.saveRemoteFile(url, destinationFilename)
2) MyLib.saveRemoteFile() downloads the image and saves it to a file by way of a thread (via an AsyncTask)
3) As soon as the image is downloaded and saved, I want to set the ImageView.setImageBitmap() using the bitmap from the saved file
I've looked at the Command pattern, but am stuck on how to implement it in this particular scenario. Any tips on this?
Maybe there is another approach that can be used? (without MyLib.saveRemoteFile() having compile-time dependencies to the UI)?
UI Fragment code snippet:
.
boolean wasSaved = MyLib.saveRemoteFile(url, destinationFilename, true)
.
.
.
Library code snippet (in a different library project):
public static boolean saveRemoteFile(String url, String filename, boolean overwriteExistingFile)
{
.
// code to check if directory exist and creates it if needed, etc, etc...
.
.
.
new AsyncTask<String, Void, Boolean>() {
#Override
protected Boolean doInBackground(String... params)
{
// code to download and save image file...
.
.
.
}
#Override
protected void onPostExecute(Boolean result)
{
// *** this is where I want to take the ImageView and set its bitmap image.
}
}.execute(new String[] {url, filename});
return retVal;
}
Design is flawed, library should have provided you Observer design pattern, using which you would have submitted listener reference along with downloading details.
Upon finishing downloading, library using your provided listener would have notified back to you over download process result, reading which you could have taken action easily with UI.
Moreover in your library code saveRemoteFile() spawns a asynctask, return value is irrelevant here as method wont wait until asynctask is executed.
Possible implementation as per above mentioned info.
// Interface for bserving
public interface DownloadListsner{
public void onSuccess(String uri);
public void onError(String uri);
}
// API for submitting download request
public void saveRemoteFile(String url, String filename,DownloadListsner listener... ){
...
}
AsyncTask{
// Upon finish execution
onPostExecute(){
// Take action
listener.onSuccess
or
listener.onError
}
}
Command pattern
You should be rather implementing Observer pattern and your download library should allow other code to attach listeners and be notified about when certain action is completed/started/whatever. And since you are just being informed that something happened you can have your code that reacts on that notification completely different in every part of your app if you need so.
I'm begining with Android development. I have an asynchronous operation, but my intention is wait the operation is completed, and after that, continue the execution of my program.
I have used AsyncTask, and all its methods, but I got error, because on the onPreExecute method I want to show another Activity, so I guess I can't show another Activity. That's the reason I want to wait to complete the asynchronous operation.
Greetings
1st edit:
I've used AsyncTask(onPreExecute, doInBa..., onPost... ), but none method works. I understand how it works the AsyncTask class, but I want stop the execution when I invoke one asynchronous thirdparty method, because in the listener that needs, I change the value of a String variable X, and after invoke my method, that uses the thirdparty method, I use the variable X. I got an exeption because the variable hasn't updated.
Please, read and follow example of AsynTask. You need to override onPostExecute
Not entirley sure what the question is but AsynTask has a method that you can call after everything has completed. A good practice is to have a dialog or a spinner showing that work is happening then dismiss it.
class loadingTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
//Do work
}
protected void onPostExecute(String s) {
ShowProgress.dismiss();
Intent myIntent = new Intent(this, PostExAct.class);
startActivity(myIntent);
}
}
In your on create:
ShowProgress = ProgressDialog.show(MainActivity.this, "",
"Loading. Please wait...", true);
new loadingTask().execute("params here");
This will show a loading dialog and while the work is being done then will be dismissed when the work is finished.
I need to show a Toast message before a method using an intense processor work. The problem is that the Toast only shows after this method, even calling this method in another Thread.
How can i show the Toast before ?
EDIT: The code is too long for showing here ... but i will resume it ...
...
Toast.makeText(getBaseContext(),"Text", Toast.LENGTH_SHORT).show();
proccess.setRun();
//In the Proccess class that implements Runnable ...
public void setRun(){
thread= new Thread(this);
thread.setPriority(Thread.NORM_PRIORITY);
thread.start();
running=true;
}
public void run() {
bytes=byteGrooveMaker();
prepare(grBytes);
}
//byteGrooveMaker() is a method in Proccess class that requires lot of processor work.
Just use an async task. On the onpreexecute you show your toast, and in the doinbackground method you execute your heavy process :)
The proper way to do "intensive" processing in Android is to use an AsyncTask.
There is (almost always) some example code in the documentation:
http://developer.android.com/reference/android/os/AsyncTask.html
Call me old fashioned for recommending a book, but O'Reilly has an excellent book "Learning Android" which walks the reader through building a complete application. Also, as a side benefit, the sample code can be downloaded (Look for the StatusActivity in the "Yamba" application for an example of AsyncTask.
Sample code can be downloaded here: http://examples.oreilly.com/0636920010883/
Try to include a little delay in the intense process thread so the Toast is shown before de process begins.