I have to display different messages in progress dialog, when running in async task.
First I need to the display the message "Please wait", then "Downloading from server", then "Please wait for sometime".
I have tried with publishProgress but when I run the application, on my ProgressDialog, only the last message "Please wait for sometime" is displayed. How can I display the three messages?
private class Sample extends AsyncTask<String, String, String> {
ProgressDialog testdialog;
#Override
protected void onPreExecute() {
testdialog = new ProgressDialog(test.this);
testdialog.setTitle("Title");
testdialog.setMessage("Please wait ");
testdialog.setIndeterminate(false);
testdialog.setCancelable(false);
testdialog.setCanceledOnTouchOutside(false);
testdialog.show();
}
#Override
protected String doInBackground(String... urls) {
publishProgress("Downloading from server");
publishProgress("Please wait for sometime");
/* here I code the background downloading process*/
}
#Override
protected void onProgressUpdate(String... pro) {
testdialog.setMessage(pro[0]);
testdialog.setMessage(pro[1]);
}
#Override
protected void onPostExecute(String result) {
testdialog.dismiss();
}
}
try this code in doInBackground() it should display all messages with 2 seconds delay for each
except last one will remain on the dialog until dialog is dismissed or hidden
#Override
protected String doInBackground(String... urls) {
try {//this should let "Please wait " appears for 2 secs
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress("Downloading from server");
try {////this should let "Downloading from server" appears for 2 secs
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress("Please wait for sometime");
try {////this should let "Please wait for sometime" appears for 2 secs
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
/* here i code the background downloading process*/
}
also for onProgressUpdate() the method is prepared to receive multi params, but you are sending only one, so no need to use pro[1], remove second setMessage() call
#Override
protected void onProgressUpdate(String... pro) {
testdialog.setMessage(pro[0]);
}
Related
I'm trying to display a "waiting" dialog while the connection is being established by the socket. Do you have any idea why this bit of code is not working ?
onProgressUpdate gets called at the end of the doInBackground. I intend to show it before connectionSocket.connect times out.
The following bit
dialog = connection.dialog("progress");
dialog.show();
works well on its own!
#Override
protected Boolean doInBackground(String... ip) {
Log.i("CONNECTION","doInBackground : Creating socket");
Boolean result = false;
try {
publishProgress();
connectionSocket = new Socket();
connectionSocket.connect(new InetSocketAddress(ip[0], connection.getServerPort()), 5000);
publishProgress();
Log.i("CONNECTION","doInBackground : Socket created");
result = true;
} catch (UnknownHostException e) {
Log.i("CONNECTION","doInBackground : Error creating socket. UnknownHostException");
} catch (IOException ioe) {
Log.i("CONNECTION","doInBackground : Error creating socket. IOException");
}
return result;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
Log.i("CONNECTION","onProgressUpdate");
dialog = connection.dialog("progress");
dialog.show();
}
Thank you for helping :*
You need to show the dialog in onPreExecute, instead of onProgressUpdate. OnProgressUpdate is to be used for long operations where you have specific percentage updates on the task at hand.
#Override
protected void onPreExecute() {
dialog = connection.dialog("progress");
dialog.show();
}
I am trying to cancel a dialog from the mainthread while the 'doInBackGround' method of AsyncTask is running. While I am downloading a photo, a progress dialog pops up and when it is finished downloading I dismis() the dialog in onPostExecute. If the connection is slow, the dialog is up for a while and I cannot cancel it until there is a timeout error or it finishes downloading. How do I use the back-button so the main thread can access. Here is what my code looks like:
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
protected void onPreExecute() {
//this piece code doesn't seem to work
progressDialog = ProgressDialog.show(context, "",
"Image loading", true);
}
protected Bitmap doInBackground(String... urls) {
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
//bmImage.setImageBitmap(result);
progressDialog.dismiss();
someMethod(result);
}
}
Use a cancellable progress dialog, pass in a cancel listener to the progress dialog and cancel the task within that method, eg
protected void onPreExecute() {
progressDialog = ProgressDialog.show(activity, "Searching files", "Scanning...", true, true,
new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// When dialog in cancelled, need to explicitly cancel task otherwise it keeps on running
cancel(true);
}
}
);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
}
You can intercept the onBackKeyPressed event, and cancel the task using cancel method.
See that link:
Ideal way to cancel an executing AsyncTask
You can try to use a ProgressDialog which is cancelable. This is the signature of the method:-
public static ProgressDialog show (Context context, CharSequence title, CharSequence message, boolean indeterminate, boolean cancelable)
In the first run of my app, i have to copy database file to data folder. it takes about 10 sec and in this period of time user sees a black screen. I want to use AsynTask technique to show a progressbar. but it doesnt work an i see that progressbar after black screen goes away...
with this code i call copy database class and also i call AsynTsk process...
new asyn().execute();
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
// throw new Error("Unable to create database");
}
and this is my AsynTask code:
public class asyn extends AsyncTask<String, Integer, String> {
ProgressDialog dialog;
#Override
protected void onPreExecute()
{
//loading toast
//final DataBaseHelper myDbHelper = new DataBaseHelper(this);
String firstload2 = myDbHelper.getfirstload();
if(firstload2.matches("1")) {
dialog=new ProgressDialog(DictionaryActivity.this);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMax(100);
dialog.show();
myDbHelper.changefirstload();
}
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
// perform desired task in this doInBackground Block.
for(int i=0;i<20;i++)
{
publishProgress(5);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "";
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
dialog.incrementProgressBy(5);
}
#Override
protected void onPostExecute(String result)
{
dialog.dismiss();
AlertDialog.Builder a=new Builder(DictionaryActivity.this);
a.setMessage("Successfully Done");
a.setTitle("Try");
a.setPositiveButton("OK",null);
a.show();
}
}
where is my fault? how i can fix that?
myDbHelper.changefirstload(); should be within the doInBackground() method. onPreExecute() executes on the UI thread.
In terms of a progress bar, that's a bit difficult here. Personally, I'd do an indeterminate progress bar (just a spinning icon or something while it loads). If you want to have a % bar, though, you will need to break up the method into multiple methods, then update your progress in between them.
please see my code .. and if you can, tell me why my progressDialog stopped when the function is halfway done in the background, the screen hangs (nothing is displayed, the logcat shows all logs i put in the background function).
Then, right before the end, the progressDialog starts animating again and closes after a couple seconds (the function is finished and the result is displayed normally)
public class changeWall extends AsyncTask<Integer, Integer, Integer> {
protected Integer doInBackground(Integer... urls) {
int totalSize=0;
try {
if(s.loadBoolean() == false)
{
log("IF = false");
log("tempLogin = "+tempLogin);
log("tempPassword = "+tempPassword);
getNewResponse(tempLogin,tempPassword);
if(needSave)
{
s.saveBoolean(true);
}
}
else
{
if(s.loadLogin()==null)
{
getNewResponse(tempLogin,tempPassword);
}else
{
getNewResponse(s.loadLogin(),s.loadPassowrd());
}
}
parser.setLol(0);
parser.startParse(RESULT_STRING);
log("end parse");
} catch (ClientProtocolException e) {
log("internet connection lost");
} catch (IOException e) {
// TODO Auto-generated catch block
log(" connection lost");
}
log("count = "+parser.getFacebookId(1));
publishProgress();
totalSize=1;
log("end of start");
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
log("wall click ON PROGRESS UPDATE");
wall.setBackgroundResource(R.drawable.tabbuttonon);
messages.setBackgroundResource(0);
activity.setBackgroundResource(0);
profile.setBackgroundResource(0);
l1_1.setBackgroundResource(R.drawable.tabbuttononleft);
l1_2.setBackgroundResource(R.drawable.tabbuttononright);
l2_1.setBackgroundResource(0);
l2_2.setBackgroundResource(0);
l3_1.setBackgroundResource(0);
l3_2.setBackgroundResource(0);
l4_2.setBackgroundResource(0);
l4_2.setBackgroundResource(0);
wall.setTextColor(Color.BLACK);
messages.setTextColor(Color.WHITE);
profile.setTextColor(Color.WHITE);
activity.setTextColor(Color.WHITE);
try {
loadWall();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
wallProgres.dismiss();
}
protected void onPostExecute(Long result) {
if(result==1)
{
log("end WallChange");
}
}
}
simple map as this showed :
----start progress(progress.show())
----start function
--- animation (progressDialog)
---animation(---)
---animation(---)
---FREEZ
---FREEZ(Function steel working normal, progressDialog in freeze mode)
---animation
---end function
---progress.dismis();//
similar problem i found here..(this problem = my problem but without download) Freezing UI Thread with AsyncTask
Regards,Peter.
It may not be correct but place
wallProgres.dismiss();
in onPostExecute rather than in onProgessUpdate method.
beacuse onProgressUpdate calls while running , but onPostExecute calls after execution.
Hope it helps..
place this line "wallProgres.dismiss()" in onPostExecute().
protected void onPostExecute(Long result) {
if(result==1)
{
log("end WallChange");
}
if(wallProgress.isShowing())
wallProgres.dismiss();
}
put this line
wallProgres.dismiss();
in onPostExecute() method
protected void onPostExecute(Long result) {
if(result==1)
{
log("end WallChange");
wallProgres.dismiss();
}
}
progressDialog = ProgressDialog.show(GetResponse.this, "", "Loading...");
new Thread()
{
public void run()
{
try
{
// inside i have written code for making connection to the server using SSL connection.
}catch (Exception e)
{
progressDialog.dismiss();
exception(e.getMessage())
}.start();
}
private void exception(String msg)
{
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
this.finish();
Intent i = new Intent(getBaseContext(), LoginPage.class);
startActivity(i);
}
my LoginPage.java is previous activity.
If the connection is successfull it goes to the next activity ot doesnt give any error,
But if der is any prob with connection then i want progress bar should be stopped and go back to the LoginPage activity and also i want the error msg to be displayed.
From the above im getting some error.. Please help me out on this
Pass in and use the context from LoginPage. Also, use the 101010 button to format your code as code in your posts.
you can go up by using try catch mechanism where in your catch place your toast message and u can do it also by asynchronous task,
here simple code
private class Task_News_ArticleView extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(
Bru_Sports_View.this);
// can use UI thread here
protected void onPreExecute() {
this.dialog.setMessage("Loading...");
this.dialog.setCancelable(false);
this.dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
//here the condition to check login details
}
} catch (Exception e) {
}
return null;
}
protected void onPostExecute(Void result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
}
and u can also use try,catch in catch block you can place your toast message
with finsih() method