I am not very clear functioning of the 'AsyncTask.
I'm trying to put a button in the ProgressDialog to cancel AsynkTask.
The problem is that when I invoke the method: runner.cancel (true);
It seems that the ProgressDialog disappears. But asynkTask continues to work in the background.
I show my code:
public class AsyncTaskRunner extends AsyncTask<String, String, String> {
#Override
protected void onCancelled(String result) {
pDialog.dismiss();
super.onCancelled(result);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setCancelable(false);
pDialog.setMessage(context.getResources().getString(
R.string.pDialog));
if (codeLink == 2) {
pDialog.setButton("cancel", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
runner.cancel(true);
}
});
}
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
// Here download the data.
}
#Override
protected void onPostExecute(String result) {
//Here I make the parser.
}
}
My guess:
it may be that doing it this way gate doInBackground () but OnPostExecute () is executed?
if it were alkoxy how do I erase everything? Also OnPostExecute () ??
AsyncTask works in background. First onPreExecute is called then doInBackground and then after completing the background task, onPreExecute is called.
just keep checking isCancelled() in the doInBackground.
protected Object doInBackground(Object... x) {
while (/* condition */) {
// work...
if (isCancelled()) break;
}
return null;
}
Related
I'm trying to display a progress dialog when sign in button is clicked. But the progress dialog is displayed only when i reach the end of my method onClick. And not a the start.
In the signIn method, i do a asynctask to reach the server.
So all the time take by the asynctask, there is no progress dialog displayed. only when the end of the onClick method is reach, the progress dialog is displayed....
Some one know what am i doing wrong?
public void onClick(View view) {
progressDialog = new ProgressDialog(SignIn.this);
progressDialog.setMessage("Sign in in progress");
progressDialog.setTitle("Please wait");
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(true);
progressDialog.show();
repSignIn = signIn(SignIn.this, etEmail.getText().toString(), etPassword.getText().toString());
if(!repSignIn.hasError())
{
Toast.makeText(getApplicationContext(), "Sign In successfully", Toast.LENGTH_SHORT).show();
onBackPressed();
}
else
{
Toast.makeText(getApplicationContext(), repSignIn.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
//progressDialog.cancel();
}
Thanks a lot in advance
Nadine
Instead of having progressDialog in onClick you need to put it in onPreExecute of your AsyncTask and dismiss it in onPostExecute.
The reason is AsyncTask uses a worker thread that will be asynchronous and that is the reason why progressDialog finishes before expected.
class MyAsyncTask extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// do your stuff
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
progressDialog.dismiss();
}
}
In Async task override onPreExecute() method and there you have to display the progress bar..
private void signIn(your parameters here) {
new AsyncTask<Void, Void, Void>(){
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(SignIn.this);
progressDialog.setMessage("Sign in in progress");
progressDialog.setTitle("Please wait");
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(true);
progressDialog.show();
}
#Override
protected void doInBackground(Void... params) {
//your logic here
}
#Override
protected void onPostExecute(JSONObject response) {
super.onPostExecute(response);
progressDialog.dismiss();
}
}.execute();
}
HOpe this helps
Use your progress dailog in Asyntask. Initialise and start your dialog in onPreExecute and dismiss dialog in onPostExecute.
working for me,
#Override
protected void onPreExecute() {
progress = new ProgressDialog(UpdateActivity.this);
progress.setCancelable(false);
progress.setMessage("Please wait data is Processing");
progress.show();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progress.dismiss();
}
I have change my code
String result = new sendDataToServer().execute(url, "PUT", jsonData.toString()).get();
By doing this:
https://gist.github.com/cesarferreira/ef70baa8d64f9753b4da
And now it's work very well.
Thanks for your help. =)
When I use AsyncTask :
class GetStreetName extends AsyncTask<String, Void, JSONObject>
{
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(getActivity());
progressDialog.setCancelable(true);
progressDialog.setMessage(getString(R.string.dialog_loading));
progressDialog.show();
}
#Override
protected JSONObject doInBackground(String... params) {
// backGround task
}
#Override
protected void onPostExecute(JSONObject result) {
if (result!=null) {
....
progressDialog.dismiss();
enterStreetEditText.requestFocus();
}
}
when I do like this, the keyboard is hiden when the dialog is dismisses in onPostExecute. How can I prevent this and keep showing the keyboard while the dialog is dismissing ?
When I do not using the ProgressDialog, the problem is not occurs.
It may help you:
#Override
protected void onPostExecute(JSONObject result) {
if (result!=null) {
....
progressDialog.dismiss();
enterStreetEditText.setFocusable(true);
enterStreetEditText.requestFocus();
InputMethodManager imm = (InputMethodManager)this.getSystemService(Service.INPUT_METHOD_SERVICE);
imm.showSoftInput(enterStreetEditText , 0);
}
}
I want to implement a progress bar while a function is getting executed.This will help me to notify user that something is going on for updation.
But I am not able to see any progressbar instead I see Logcat message as progressBar dimensions.
class Async extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute()
{
ProgressDialog progress=new ProgressDialog(App_list_Activity.this);
progress.setTitle("Please Wait while sync is in progress!!");
progress.setMessage("Database is getting updated...");
progress.setCancelable(true);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.show();
}
#Override
protected String doInBackground(Void... arg0)
{
updateDatabase();
return null;
}
#Override
protected void onPostExecute(String result)
{
ProgressDialog progress=new ProgressDialog(App_list_Activity.this);;
progress.dismiss();
}
}
new Async().execute();
Where am I going wrong?
As the Android documentation states :
onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
Try this:
private ProgressDialog progress;
class Async extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute()
{ progress= new ProgressDialog(SingleContactActivity.this);
progress.setTitle("Please Wait while sync is in progress!!");
progress.setMessage("Database is getting updated...");
progress.setCancelable(true);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.show();
}
#Override
protected String doInBackground(Void... arg0)
{
updateDatabase();
return null;
}
#Override
protected void onPostExecute(String result)
{
if (progress.isShowing())
progress.dismiss();
}
}
new Async().execute();
}
Declare ProgressDialog at class level :
class Async extends AsyncTask<Void, Void, String> {
ProgressDialog progress;
Initialize in onPreExecute() :
protected void onPreExecute() {
progress=new ProgressDialog(App_list_Activity.this);
Dismiss in onPostExecute() :
protected void onPostExecute(String result){
progress.dismiss();
In your code you again Initialize ProgressDialog in onPostExecute() for dismiss onPreExecute ProgressDialog so it will create new ProgressDialog instance and dismiss it but still onPreExecute() ProgressDialog is not dismiss.
Example :
class Async extends AsyncTask<Void, Void, String> {
ProgressDialog progress;
#Override
protected void onPreExecute()
{
progress=new ProgressDialog(App_list_Activity.this);
progress.setTitle("Please Wait while sync is in progress!!");
progress.setMessage("Database is getting updated...");
progress.setCancelable(true);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.show();
}
#Override
protected String doInBackground(Void... arg0)
{
updateDatabase();
return null;
}
#Override
protected void onPostExecute(String result)
{
progress.dismiss();
}
}
new Async().execute();
You are creating one instance in onPreExecute and another in onPostExecute. You should keep the reference and dismiss that one.
On top of that I suggest keeping the member progress final, otherwise Android might scream about leak.
Furthermore, dismiss dialog should be in onCancelled as well.
class Async extends AsyncTask<Void, Void, String> {
private final ProgressDialog progress;
public Async(Context c) {
super();
this.progress = new ProgressDialog(c);
progress.setTitle("Please Wait while sync is in progress!!");
progress.setMessage("Database is getting updated...");
progress.setCancelable(true);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
}
#Override
protected void onPreExecute() {
progress.show();
}
#Override
protected String doInBackground(Void... arg0) {
updateDatabase();
return null;
}
#Override
protected void onPostExecute(String result) {
if (progress.isShowing()) {
progress.dismiss();
}
super.onPostExecute(result);
}
#Override
protected void onCancelled() {
if (progress.isShowing()) {
progress.dismiss();
}
super.onCancelled();
}
}
new Async().execute();
HTH.
I'm trying to use HttpManager to retrieve a String from a url
public String request(Context context, String url){
page_requested = "empty";
HttpQuery query = new HttpQuery(context, mHttpClient);
query.execute(url);
return page_requested;
}
and use it in MainActivity
public void onClick(View v) {
Toast.makeText(MainActivity.this, HttpManager.getInstance().request(MainActivity.this, "http://myurl"), Toast.LENGTH_SHORT).show();
}
But public String request doesn't wait for query to be executed and returns "empty" but if I wait 10sec to display the toast, it returns the correct value.
What's the best way to display the expected value?
Use AsyncTask to display your text. I think this will be an efficient way.. you can show your progressbar while loading the operation.
public class DisplayString extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
dialog.setMessage("Please wait...");
dialog.setCancelable(false);
dialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
// Things to be done while execution of long running operation is in progress. For example updating ProgessDialog
}
#Override
protected void onPostExecute(Void result)
{
//Post Execute
dialog.cancel();
//Display your string here
}
#Override
protected Void doInBackground(Void... params) {
// Your operation..Dont Edit Any Views here
return null;
}
}
Hope it helps
I have a time consuming task that is taking place in the doInBackground() method, but from within that method, I want to be able to update the progressDialog with percentage data. How can I do this?
class GetDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute()
{
mProgressDialog = ProgressDialog.show(getActivity(),Constants.APP_NAME,"Getting data", true);
}
#Override
protected Void doInBackground(Void... params)
{
//go get data, update mProgressDialog
return null;
}
#Override
protected void onPostExecute(Void res)
{
}
}
Override the onProgressUpdate() method like this:
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mProgressDialog.setProgress(progress[0]);
}
and publish the progress with
publishProgress((int) (total * 100 / fileLength));
Try to refer to this link
AsyncTask has method onProgressUpdate(Integer...) that you can call each iteration for example or each time a progress is done during doInBackground() by calling publishProgress().
Refer to the docs for more details
Note that the second parameter is the progress variable
class GetDataTask extends AsyncTask<Void, String, Void> {
#Override
protected void onPreExecute()
{
mProgressDialog = ProgressDialog.show(getActivity(),Constants.APP_NAME,"Getting data", true);
}
#Override
protected Void doInBackground(Void... params)
{
publishProgress(""+(int)count);
return null;
}
protected void onProgressUpdate(String... progress) {
/**
* Sets current progress on ProgressDialog
*/
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(Void res)
{
}
}