Toast and Async - android

I have a toast in a slave thread which needs to tell a user wen a connection is established. To do this I know I need to use Async to make the toast happen, but I'm not sure where or how to implements the extended async. If I understand it, I think I can just create a MyAsync with the and just onProgressUpdate() the toast?
#Override
public void onProgressUpdate(String... args) {
Toast.makeText(context, args, Toast.LENGTH_SHORT).show();
}
Thanks for your time
~Aedon

Yep, you should be able to just extend the ASyncTask and change the template variables to what you need. The Toast class is a static class so it can be called from any thread without worrying about conflicts.
I don't see any issues with your code above except you wouldn't want to be calling new Toast messages very often since they stack. So if you were to continuous call the .show() function it would stack them and continue to show new Toast messages every LENGTH_SHORT interval until it caught up.
As for an example of an ASyncTask, here you go:
private class MyAsync extends AsyncTask<<What to pass in to doInBackground>, <What to pass in to onProgressUpdate>, <What type onPostExecute receives>> {
protected T (result type to onPostExecute) doInBackground(T... urls) {
//Do big calculations in here
}
protected void onProgressUpdate(T... progress) {
//Update
}
protected void onPostExecute(T result) {
//Done
}
}

Related

How to do or do nothing base on AsyncTask result?

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().

ProgressDialog vs. AsyncTask - won't show

I know this question has been asked multiple times, but I have an apparently clean code that just doesn't work, giving me no Exceptions or anything.
I have a trivial one-button Activity (MainActivity). The button in it calls an AsyncTask in order to send an email in the background. I tried to do what I guess it's a pretty common thing: show a ProgressDialog when the task starts and dismiss it when it ends. To do so I put the above-mentioned code into AsyncTask.onPreExecute() and AsyncTask.onPostExecute().
I thought the problem was in the Context provided to the dialog constructor, but I created a simple constructor for my AsyncTask to which I pass the application context. I added a simple Toast to debug, but it doesn't show up neither...
Here's the code for the button onClick method:
public void onClick(View v) {
new Sender(this).execute("args");
}
And here's the code for the task:
private class Sender extends AsyncTask<String, Void, Void> {
private ProgressDialog progDialog;
private Context context;
public Sender(Context context) {
this.context = context;
}
#SuppressWarnings("unused")
protected void onPreExecute(Void... params) {
Toast.makeText(this.context, "Sending...", Toast.LENGTH_SHORT).show();
progDialog = ProgressDialog.show(this.context, "Sending", "Picture is being sent...", true);
}
protected Void doInBackground(String... mailSubj) {
// some code that works
return null;
}
#SuppressWarnings("unused")
protected void onPostExecute(Void... v) {
progDialog.dismiss();
Toast.makeText(MainActivity.this, "Mail sent", Toast.LENGTH_SHORT).show();
}
}
Where did I go wrong?
Your progress dialog not show up because you don't override onPreExecute(). Add #Override annotation to your onPreExecute(), see what happens. onPreExecute takes no arguments.
I found the mistake and the solution is straight forward: adding a Void list of arguments to onPreExecute() and onPostExecute() caused Java to not override the methods from AsyncTask. The first needs no arguments and the latter needs a single Result (in this case Void) argument.
This question can be closed.

How to work with AsyncTask and threads?

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.

ProgressDialog communicate with AsyncTask in android

Tips or ideas on how ProgressDialog can communicate with asyncTask.
For example when I click the button, the program will validate the input to internet, This is should not be interupted. so I use ProgressDialog.
After progressDialog.dismiss(), I need to refresh the view by calling the asyncTask.
I have tried some ways but it's failed, for example
* I execute asynTask after progressdialog.dismiss().
* put execution asynctask inside dialogbox after progressdialog thread.
in other word, is there any way to tell asynctask that progressdialog has been dismissed. Or is there communication such as message between threads ?
here is the example of my code:
btnPost.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
stockProgressDialog = ProgressDialog.show(PostActivity.this,
"Please wait...", "Check the post");
new Thread() {
public void run() {
try{
/* Connect to Internet API */
stockProgressDialog.dismiss();
} catch (Exception e) { }
// Dismiss the Dialog
}
}.start();
new LookUpTask().execute();
}
});
Yes, there is a way to tell asyncTask that progressDialog has been dismissed. you can use one onDismissListener
#Override
public Dialog onCreateDialog(int id){
if(id==DIALOG_PROGRESS_DIALOG){
stockProgressDialog = new ProgressDialog(Main.this);
stockProgressDialog.setTitle("Please wait...");
stockProgressDialog.setMessage("Check the post");
stockProgressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
textView.setText("Waiting the 5 secs...");
myAsyncTask.execute("start it");
//Or myAsyncTask.cancel(true); if you want to interrupt your asyncTask
}
});
return stockProgressDialog;
} else return super.onCreateDialog(id);
}
You can cancel an AsyncTask by calling AsyncTask.cancel(..) and then start up a new AsyncTask. You are not supposed to run the AsyncTask as a parallel activity - it is supposed to be able to run and finish without outside intervention.
Extend async and look into returning a result from doInBackground. onProgress update can dismiss your Progress dialog under control of the async task. Handle the result from doInBackground in onPostExecute.
//create the task
theBackground = new Background();
theBackground.execute("");
--------
private class Background extends AsyncTask<String, String, String>{
protected String doInBackground(String...str ) {
publishProgress("##0");
//do a bunch of stuff
publishProgress(#001);
return("true");
}
protected void onProgressUpdate(String... str ) {
//do stuff based on the progress string and eventually
myProgressDialog.dismiss();
}
protected void onPostExecute(String result) {
}
}
I'm not sure why you're using a thread in one case, but an AsyncTask in another when you could just use two AsyncTasks... Actually, unless I'm missing something, in your case the most straightforward way is to combine the two bits of work into one AsyncTask and simply create and destroy the dialog in the AsyncTask callbacks. In pseudo-code:
onPreExecute
show dialog
doInBackground
do internet stuff
onPostExecute
update views
close dialog
Is there a reason why you're trying to update the views in its own AsyncTask? If you're updating views, you probably need to do the work in the UI thread anyway...

Android - Problem with AsyncTask

I needs to make a call to a webservice for 5 times(as there are 5 different parameters) one by one or all at once. Once a particular call completed, in background a textview should be updated with text as: "1st completed", "2nd Completed" and so on.
TextView value should be updated in background.
What should i do ? I am knowing the concept of AsyncTask, but i am confused that should i write 5 AsyncTask and then for each i write execute() method to execute the AsyncTask?
I am successful for only 1 one call, as i set "1st completed" in postExecute() method. But confused for the 5 times call.
Please suggest me a better way or exact solution.
You only need 1 AsyncTask, you have to do all 5 calls in the doInBackground() and everytime you complete one call the publishProgress passing for example the number of the completed call, then, at the end do whatever you need in onPostExecute.
A simple approach:
private class ServiceCallTask extends AsyncTask<String, Integer, Void> {
protected void onPreExecute() {
//prepare whatever you need
myTextField.setText("starting calls");
}
protected Void doInBackground(String... params) {
//process params as you need and make the calls
doCall1();
publishProgress(1); //this calls onProgressUpdate(1)
doCall2();
publishProgress(2);
doCall3();
publishProgress(3);
doCall4();
publishProgress(4);
doCall5();
publishProgress(5);
return;
}
protected void onProgressUpdate(Integer... progress) {
//this runs in UI thread so its safe to modify the UI
myTextField.append("finished call " + progress);
}
protected void onPostExecute(Void unused) {
myTextField.append("all calls finished");
}
}

Categories

Resources