I am trying to get along with AsyncTask..
what my problem was that i was building a table of textviews dynamically, based on the output of a procedure.. But then i figured that by using asynctask i can do it in a more efficient way..So, what i did is as follows:
private class DisplayReport extends AsyncTask<Void, Void, Boolean>{
protected void onPreExecute(){
//Message -- "Please wait while the Report Loads..."
}
#Override
protected Boolean doInBackground(Void... params) {
//Here i fetch the data from the procedure via a web service
//parse the result of web service and set a bool variable true or false based on whether the dataset fetched is empty or not.
}
protected void onPostExecute(Boolean value){
if(value == true){
"Please try again later!!"
}
else{
runOnUiThread(GenTable);
}
}
private Runnable GenTable = new Runnable(){
public void run(){
try {
displayReport(result); // in this method i build the table.
} catch (Exception e) {
ad.setTitle("Error..");
ad.setMessage(e.toString());
}
}
};
}
the above async class is an inner class in my main class which extends activity.
and this is how i am executing the asynctask..
DisplayReport dr = new DisplayReport();
dr.execute();
now when i debug, i get the "source not found" error on dr.execute()..
i tried searching a lot on the net, but i simply cannot find out anything concrete. Also, please let me know if my approach is incorrect..
this question might seem very silly, but i am new to android and java as well and any help would be really great..
Thanks!
Execute is going to start a new thread. You don't want to debug into it. Instead, put breakpoints in onPreExecute, doInBackground, and onPostExecute and you can see when each of those gets called.
onPostExecute is already being run in the UI thread, so you should not create another runnable for it. Just make your onPostExecute like this:
protected void onPostExecute(Boolean value){
if(value == true){
String message = "Please try again later!!";
// Do something here with your message
}
else{
displayReport(result);
}
}
Related
Experts,
My goal is simple, input an address, click a button to test a URL, if not get the expected result, a toast info and then do nothing. If get expect result, continue the program.
Since I can not use URL in UI thread, I used AsyncTask, the problem is: though I know the result from AsyncTak, how to inform activity to do or do nothing?
What I want is a statement inside the OnClickListener like this:
if (result is not expected) return; else continue do things.
I cannot write above statement in onPostExecute, it will return onPostExecute(), not onClickLIstener().
Another is: even if I can pass the result to activity(namely to onClickLIstener()), when the result arrives, probably UI thread already run some other codes, but they shouldn't before knowing the result.
In short, I need the URL result to decide how to run remaining codes, therefore cannot use async task, what should I do?
Thanks.
Below is the example code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
btnConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new XXX().execute(code);
});
}
class XXX extends AsyncTask<String, Void, String> {
protected String doInBackground(String... strArr) {
XXXXX;
}
protected void onPostExecute(String result) {
XXXXX;
}
}
This should be easy. Try this approach:
Since you already have your AsyncTask as an inner class in your activity, you can easily return a result in onPostExecute() then check if request was successful or not.
Now, here is the final part: create a method in your activity like this:
private void executeOnAsyncSuccess(){
//place the code here you want to run
}
Now you can call it inside onPostExecute() easily!
You can also do this using Events but this approach should just work!
I hope this helps!
I just learned that maybe Callable is a good way, use its V get().
I need to call task() function from doInBackground() of AsyncTask class. The task function contains 2 sub-async task. So the task() return immediately from doInBackground().
Is it possible to stop(or mark this task done) this task from anywhere else?
How to wrap two sub async task in one.
You don't need to call another AsyncTask from within doInBackground. As a matter of fact, once you get to a high enough API, you'll get an exception. You can call another long running method from within AsyncTask without needing to worry about a thread; you're already in a background thread. If you really feed the need, call another service, but there is no reason to do this.
To stop an AsyncTask, just override OnCancelled. Then you can just call:
task.cancel(true).
EDIT:
If you want to wait for another process to finish before you move on, you can wait for that process to finish by setting a global variable in your class or application and then doing a Thread sleep until done. You will not get an ANR because you are already in a background thread and not on the Main UI:
private boolean processIsDone = false.
//then in your method you are calling from AsyncTask:
private void myLongRunningMethod() {
//do your work here....
//at the end set
processIsDone = true;
}
//in your AsyncTask:
protected Void doInBackground(Void... params) {
//do first part of AsyncTask here
myLongRunningMethod();
do {
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (!processIsDone);
//finish the process here.
return null;
}
I do not understand the question exactly but maybe this can help. Use this class in your Activity like this:
myTask = new BackgroundAsyncTask().execute();
And cancel this way:
myTask.cancel(true);
This is the code of the class:
private class BackgroundAsyncTask extends AsyncTask<Object , Object ,String> {
protected void onPreExecute(){
// Do Before execute the main task
}
protected String doInBackground(Object... param) {
//Execute the main task and return for example and String
return res;
}
protected void onPostExecute(String result) {
// You can use the String returned by the method doInBackground and process it
}
}
Hope it's help
About your first question, you can catch event when your task is cancelled by onCancelled() method. try like this:
private CancelTask extends AsyncTask {
private boolean cancelled = false;
protected void onCancelled() {
cancelled = true;
}
protected Object doInBackground(Object... obj) {
do {
// do something...
}while(!cancelled)
}
}
and call AsyncTask.cancel(true); when you want to stop.
CancelTask task = new CancelTask();
task.execute();
...
task.cancel(true);
And about second question, I want to know how you handle two "Sub-AsyncTask"s.
I will try to find a solution after you update your code.
I am trying to trigger a HTTP post request on each button click to get some data from a webservice in android. I have created an async task to send the http request. My code is as follows :
Activity
public void sendHttpRequest(View view){
//gets called on button click
new MyHttpRequestTask(this).execute();
}
MyHttpRequestTask
public class MyHttpRequestTaskextends AsyncTask<Void, Void, Void> {
#Override
protected void onPostExecute(Void result) {
//Show received data
super.onPostExecute(result);
}
#Override
protected Void doInBackground(Void... arg0) {
//Send http request
return null;
}
}
I am having two problems, one is that the onPostExecute method is not being fired and the other is, if I press the button second time or multiple times, the task is not being executed. But somehow I think that onPostExecute method not being called is the reason for the task not being executed on second time. So, what am I doing wrong? How can I get rid of these issues? Thanks
Here is the full doInBackground method
#Override
protected Void doInBackground(Void... arg0) {
Looper.prepare();
GpsHelper gpsHelper = new GpsHelper();
LocationHelper locationHelper = new LocationHelper(mContext);
gpsHelper.turnGPSOn();
String location = locationHelper.getMyCurrentLocation();
...
String rawHtml = HttpHelper.sendPostRequest(postUrl, postParams);
HtmlHelper.processRawHtml(rawHtml);
Looper.loop();
return null;
}
It gets the current location using GPS, then the current address and posts them to a webservice, then the response from webservice is parsed and processed. Is the problem due to the GPS ?
Here you should call your method like
public MyHttpRequestTask myHttpRequestTask;
public void sendHttpRequest(View view){
//gets called on button click
//Status.PENDING -- got the status when your asynch task not run yet with same instance
//Status.RUNNING -- whether it running
if(myHttpRequestTask.getStatus() == Status.FINISHED || myHttpRequestTask.getStatus() == Status.PENDING){
myHttpRequestTask = new MyHttpRequestTask(this).execute();
}
}
if your asynch task is in running task then no need to start it again and it would not be start.
it would be feasible if you create a new object when your status of asynchtask is either finish or pending. and please put the log or system out in your post method so you can easily identify it whether it will be called. please check again.
Please do this in your code,
public void sendHttpRequest(View view){
//gets called on button click
new MyHttpRequestTask().execute();
}
public class MyHttpRequestTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
//Send http request
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//please put your code here.
}
}
try this code, and if any issues then please mention here.
After couple of days of head banging and debugging, I finally figured it out.
The onPostExecute was not being executed because of the GPS codes. Apparently, starting gps started few threads which were not terminated and hence onPostExecute was not being executed.
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 have listed of products with different category. I have to sort them. Because of the queries, It is taking more time to load. Between two activities, the screen is coming black. I want to run the query in the background. How can I do that and how to use its result in main activity?
private class InsertTask extends AsyncTask {
String cat;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(String... params) {
Boolean success = false;
try {
category(cat);
success = true;
} catch (Exception e) {
if(e.getMessage()!=null)
e.printStackTrace();
}
return success;
}
#Override
protected void onPostExecute(Boolean success) {
super.onPostExecute(success);
}
private void category(String category) {
try{
Cursor1 = mDbHelper.fetchcategory(category);
}catch(Exception e){
Log.v("Excep", ""+e);
}
}
And when called
InsertTask task = new InsertTask();
task.execute();
I have listed the category in buttons. How can I get the values then?
You should use AsyncTask for that. And some more info.
Its good you have thought of AsyncTask. Firstly, you can declare this class as inner in you class activity (if you haven't previously did) and so you are able to access you view class members.
You can do this also by creating thread and one handler that will be used to update your UI components. Remember that if you use threads you'll need to lock/unlock your database object because of the thread safety(if any other thread is accessing the database for any reason). Read more about thread safety of dbs.
I was doing some searching myself, and I came across this read, its rather long but looks extremely helpful, with lots of code examples. (I bookmarked it for myself).
Threads, Async, and Handlers O MY!
But some form of threading is the ticket.
From Android dev.
(My favorite code snippet)
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
//Do Work here
}
}).start();
}