progressDialog and AsyncTask - android

I would like to create a dialog with a progress bar inside.
But I see the Toas message, but I don't see the dialog and tre progress bar ..why?
thx a lot for evryone.
//prepare for a progress bar dialog
progressBar = new ProgressDialog(this);
progressBar.setCancelable(true);
progressBar.setMessage("Creazione Database\nIngredienti...");
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setProgress(0);
progressBar.show();
new BackgroundAsyncTask(appContext, progressBar).execute();
...
...
...
and i have created a generic class:
public class BackgroundAsyncTask extends AsyncTask<Void, Integer, Void> {
int myProgressCount;
Context context;
ProgressDialog progressBar;
public BackgroundAsyncTask(Context appContext, ProgressDialog progressBar) {
// TODO Auto-generated constructor stub
this.context = appContext;
this.progressBar = progressBar;
}
#Override
protected void onPreExecute() {
Toast.makeText(context, "onPreExecute Start Progress Bar", Toast.LENGTH_LONG).show();
progressBar.setProgress(0);
myProgressCount = 0;
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
while (myProgressCount < 100) {
myProgressCount++;
/**
* Runs on the UI thread after publishProgress(Progress...) is
* invoked. The specified values are the values passed to
* publishProgress(Progress...).
*
* Parameters values The values indicating progress.
*/
publishProgress(myProgressCount);
SystemClock.sleep(100);
}
return null;
}
/**
* This method can be invoked from doInBackground(Params...) to publish
* updates on the UI thread while the background computation is still
* running. Each call to this method will trigger the execution of
* onProgressUpdate(Progress...) on the UI thread.
*
* onProgressUpdate(Progress...) will not be called if the task has been
* canceled.
*
* Parameters values The progress values to update the UI with.
*/
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
progressBar.setProgress(values[0]);
}
#Override
protected void onPostExecute(Void result) {
Toast.makeText(context, "onPostExecute End Progress Bar",Toast.LENGTH_LONG).show();
progressBar.dismiss();
}
}

The progress range is 0..10000. - as the docs says. Use numbers that fit that range.

I highly recommend use dialog fragment instead dialog
public class ProgressDialogFragment extends DialogFragment {
public static LoadingDialogFragment newInstance() {
ProgressDialogFragment frag = new ProgressDialogFragment ();
return frag;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final ProgressDialog dialog = new ProgressDialog(getActivity());
dialog.setMessage(getString(R.string.loading_text));
dialog.setIndeterminate(true);
dialog.setCancelable(false);
// Disable the back button
OnKeyListener keyListener = new OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode,
KeyEvent event) {
if( keyCode == KeyEvent.KEYCODE_BACK){
return true;
}
return false;
}
};
dialog.setOnKeyListener(keyListener);
return dialog;
}
}
More info here https://gist.github.com/dhawalhshah/1355547

Related

Upadate progressdialog message

I have one AsyncTask and I am setting message of ProgressDialog within onPreExecute() method. Now I want to update message of ProgressDialog within method which is called from StartUpload() method of doInbackground.
class performBackgroundtask extends AsyncTask<Void, Void, Void> {
// #Override
public void onPreExecute()
{
connectionProgressDialog = new ProgressDialog(ProcessReportsUploadActivity.this);
connectionProgressDialog.setCancelable(false);
connectionProgressDialog.setCanceledOnTouchOutside(false);
connectionProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
connectionProgressDialog.setMessage("Uploading data...");
connectionProgressDialog.show();
}
// #Override
public Void doInBackground(Void... params)
{
try
{
StartUpload();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
// #Override
public void onPostExecute(Void result)
{
connectionProgressDialog.dismiss();
connectionProgressDialog.cancel();
}
}
use publish progress in DoInBackground
publishProgress(""+(int)((total*100)/lenghtOfFile));
and update progess bar in onProgressUpdate
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
you can use onProgressUpdate
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.
#Override
protected void onProgressUpdate(Integer... progress) {
// setProgressPercent(progress[0]);
//set prograss to your prograss dialoglike this
connectionProgressDialog.SetProgress(progress);
}

unable to show a progress bar properly

i want to show in my activity a progress bar as a response to a button click.
i read in another question that i should use async task in order to show/not show the progress bar but when i click on the button the progress bar is not shown properly (it appears for much less time then it should)
any suggestions?
the activity code:
public void chooseContactFromList(View view){
ProgressBar pBar = (ProgressBar) findViewById(R.id.progressBar1);
circleActivity progressTask = (circleActivity) new circleActivity(pBar).execute();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
CharSequence[] cs=nameList.toArray(new CharSequence[nameList.size()]);
builder.setTitle("Make your selection");
builder.setItems(cs, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
reciverNumber = phoneList.get(item);
}
});
AlertDialog alert = builder.create();
alert.show();
progressTask.cancel(true);
}
the AsyncTask code:
public class circleActivity extends AsyncTask<Void, Void, Void> {
private ProgressBar progressBar;
public circleActivity(ProgressBar pBar) {
progressBar=pBar;
}
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(Void result) {
progressBar.setVisibility(View.INVISIBLE);
}
#Override
protected void onProgressUpdate(Void ... progress) {
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
return null;
}
}
thanks
As you are doing nothing in the doInBackground(), the progressBar is shown for few moments only. If you really want to see it, then try doing some operation in doInBackground() which will take some time.
eg. Try Thread.sleep(1000); in doInBackground to test it.
And I suggest you to refer following links.
http://www.vogella.com/articles/AndroidBackgroundProcessing/article.html
http://developer.android.com/reference/android/os/AsyncTask.html

AsyncTask Class Showing Null Pointer Exception in onProgressUpdate Method

I am a beginner in android. I am trying to control a progressbar with AsyncTask in a class that extends android's inbuilt messenger class. I am getting an Exception but, can't understand the fault in my code.
public class MyMessenger extends Service {
private ProgressDialog downloadProgressDialog;
static final int v1=1,v2=2;
ProgressBar bar;
class MyHandler extends Handler
{
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case v1:
Toast.makeText(getApplicationContext(), "message = 1 in handler of messenger", Toast.LENGTH_LONG).show();
break;
case v2:
new sync().execute();
break;
}
}
}
Messenger messenger=new Messenger(new MyHandler());
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
//Toast.makeText(getApplicationContext(), "binding...", Toast.LENGTH_LONG).show();
return messenger.getBinder();
}
public class sync extends AsyncTask<Void, Integer, Void>
{
int progress=0;
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
// super.onProgressUpdate(values);
downloadProgressDialog.setProgress(values[0]);
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
while (progress<100) {
progress++;
publishProgress(progress);
SystemClock.sleep(1000);
}
return null;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
downloadProgressDialog = new ProgressDialog(getApplicationContext());
downloadProgressDialog.setMessage("Downloading file...");
downloadProgressDialog.setMax(100);
downloadProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
downloadProgressDialog.setCancelable(false);
downloadProgressDialog.show();
}
}
}
Since you are unable to findViewById in service , do the same in your activity that starts the service and make bar as a public static variable.bar is null because you have not initialsed it by findViewById
public static ProgressBar bar = (ProgressBar) findViewById(R.id.progressbar);//in activity
Code in async task
//async task
#Override
protected void onProgressUpdate(Integer... values) {
if(!MyActivityName.bar=null)
MyActivityName.bar.setProgress(values[0]);
super.onProgressUpdate(values);
}
Hope this works.
You never initialize bar, so it is null when you use it at bar.setProgress(values[0]).
because you didn't initialize your progress bar. initialize like below:
bar = (ProgressBar) findViewById(R.id.progressbar);
EDIT:
Then you have to use Progressdialog rather than progress bar like below:
private ProgressDialog downloadProgressDialog;
protected void onPreExecute() {
super.onPreExecute();
downloadProgressDialog = new ProgressDialog(context);
downloadProgressDialog.setMessage("Downloading file...");
downloadProgressDialog.setMax(100);
downloadProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
downloadProgressDialog.setCancelable(false);
downloadProgressDialog.show();
}
and then use dialog object in your progressupdate method.
EDIT:
Via Binder you can send callbacks to your Activity, which means that you can update UI like progress dialog.
Add according method to your Binder (let's name it onProgress)
From your AsyncTask call method of this Binder
In order to know about progress updates consider using Observer pattern (in other words - your Activity should listen for updates of your Binder, or more specifically - of calling Binder.onProgress method)
You can not to show progress dialog , You have extend service class that is used to run thread in background. just use only doinbackground() method, remove progress dialog method
.

How to show dialog box from asyntask nonUI activity in android?

i have implemented code form the below link to check the idle time of the application
How to intent to another page on android/pop up a message from idle time?
Instead using thread i used asyntask...Now my problem once it reaches the idle time..i want to show dialog to the user application is end relogin from the login activity..
How can i call dialog from the asynctask onpostExcute
public class session extends AsyncTask<Void,Void,Void> {
private static final String TAG=session.class.getName();
private long lastUsed;
private long period;
private boolean stop;
Context context;
final Dialog dialog = new Dialog(context);
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
//here i do the process.......
}
#Override
protected void onPostExecute(Void x){
//stuff to be done after task executes(done on UI thread)
// For Dialog Button**********************************
dialog.setContentView(R.layout.dialog);
dialog.setTitle("Result");
final TextView dialogtxt = (TextView) dialog
.findViewById(R.id.textView1);
final Button closeButton = (Button) dialog
.findViewById(R.id.button1);
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
dialogtxt.setText("session time out");
dialog.show();
// ****************************************************
}
#Override
protected void onPreExecute(){
//stuff to be done after task executes(done on UI thread)
}
}
You can do it by calling the dialog from either one of the methods except the doInBackground method.
You may call it in the onPreExecute and show the dialog there and after your background task is done you can cancel it from the onPostExecite method. If you want even more control you can also do it using onProgressUpdate. Just dispatch the progress from your background task by calling publishProgress and overwrite the onProgressUpdate method and do whatever you want there.
This is an example taken right out of the docs.
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
The Asynctask need to get the Context.
If your Asynctask is embeded into the activity, just call the java Activity.this as a context.
You can also put a context as a field in the Asynctask and then give it as an arg to Asynctask.
You can call the Dialog.show in the onPostExecute, it's on UI Thread.
This sample AsyncTask is embeded into an activity
public class AsyncDialogBuilder extends AsyncTask {
private Context context = DriverOnTripActivity.this;
private final AlertDialog.Builder dialog = new AlertDialog.Builder(context);
private Integer remoteAllWaitinOnCount;
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
}
#Override
protected Integer doInBackground(Integer... integers) {
remoteAllWaitinOnCount = User.getRemoteAllWaitinOnCount(latestClosestKojo.getRemoteId());
if (remoteAllWaitinOnCount > 0) {
try {
makeDialog();
} catch (Exception e) {
e.printStackTrace();
}
return 100;
} else {
return 99;
}
}
private void makeDialog() {
dialog.setTitle(latestClosestKojo.getName()
+ " - "
+ remoteAllWaitinOnCount
+ " Kojoalas");
dialog.setPositiveButton("S'arreter", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
isDialogPrompted = false;
dialogInterface.dismiss();
goToOnBoardingActivity();
}
});
dialog.setNegativeButton("Ignorer", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
isDialogPrompted = false;
dialogInterface.dismiss();
}
});
}
#Override
protected void onPostExecute(Integer integers) {
if (integers >= 100 && dialog != null) {
dialog.show();
isDialogPrompted = true;
}
}
}

showing imported data on progress bar

I am working on Address book app in android.In my application i import contacts from phonebook in my app.while importing i am showing progress bar.I want to show the contacts being imported on the progressbar while importing.how to do this?
following is my code:-
public class Task extends AsyncTask<String, Integer, Void> {
private ProgressDialog dialog;
protected Context applicationContext;
#Override
protected void onPreExecute()
{
System.out.println("IN PreExecute");
this.dialog = ProgressDialog.show(applicationContext, "Importing Contacts", "Please Wait...", true);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
System.out.println("IN BACKGROUND");
addcontacts();//return flag1;
//dialog.setMessage(name);
return null ;
}
protected void onProgressUpdate(String... progress)
{
System.out.println("IN update");
}
#Override
protected void onPostExecute(Void unused) {
this.dialog.cancel();
System.out.println("IN PostExecute");
final AlertDialog.Builder alertbox1=new AlertDialog.Builder(Import.this);
Cursor c=data.getData();
int num=c.getCount();
alertbox1.setMessage(+num+" contacts imported");
c.close();
// set a positive/yes button and create a listener
alertbox1.setPositiveButton("OK", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1)
{
call();
}
});
alertbox1.show();
}
onProgressUpdate gets called every time we call publishProgress and the arguments from publishProgress go to onProgressUpdate
So in doInBackground() you can do
protected Void doInBackground(String... params) {
for(int i=1; i<=totalContacts; ++i) {
importNextContact();
publishProgress(i/(float)totalContacts)*100);
}
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
Using dialog.setMessage("msg") is correct but remember that you can not change the ui in the
doInBackground(...) method, so either you post a msg using an handler or you use runOnUiThread.

Categories

Resources