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.
Related
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]);
}
I have read all solutions for the same question, but did not seem to find a answer.
I have a ProgressDialog which I am showing in the onPreExecute() of a AsyncTask. It does not dismiss after the doInBackground() is finished.
Here is my code:-
Main.java
case R.id.action_refresh:
new RefreshItems().execute();
return true;
private class RefreshItems extends AsyncTask<Void, Void, Void>
{
ProgressDialog refDialog ;
Fragment fragment = null;
List<News> updatedList;
#Override
protected void onPostExecute(Void result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
if(refDialog!=null && refDialog.isShowing() && refDialog.isIndeterminate())
refDialog.dismiss();
}
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
refDialog = ProgressDialog.show(Home.this, "", "Please wait", true, false);
}
#Override
protected Void doInBackground(Void... params)
{
// TODO Auto-generated method stub
try
{
updatedList = new GetList().execute(items).get();
fragment = new HomeFragment(SPHostUrl,encodedAccountName,deviceAuthKey,usersname,avatarUrl, fullName,getApplicationContext(),updatedList);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
// TODO Auto-generated method stub
}
problem:
refDialog.isIndeterminate()
You are not measuring something so it will return false, so it is not dismissing your dialog.
solution:
remove it in your if statement
if(refDialog!=null && refDialog.isShowing())
Also remove this:
super.onPostExecute(result);
you dont need the default onPostExecute;
Edit:
problem 2:
ProgressDialog.show(Home.this, "", "Please wait", true, false);
you set the cancelable to false which mean you can not cancel it upon dismissing.
change your showing of dialog to this:
refDialog = ProgressDialog.show(Home.this, "", "Please wait")
Your below condition is becoming wrong in any manner,
if(refDialog!=null && refDialog.isShowing() && refDialog.isIndeterminate())
Just remove that condition and simply dismiss your dialog,
refDialog.dismiss();
Or,
Check your condition, that in which case its becoming wrong.
remove if(refDialog!=null && refDialog.isShowing()) from onPostExecute and it will work
if you really need to know if it is showing you can create a boolean visible=false; in the class set it true on preExecute ant check it on Post Exec
Make dialog field refDialog static and then try it
public static ProgressDialog refDialog ;
I am creating an app in which I have to fetch some data from Internet and show it to user on UI.
I have create an progress bar in AsyncTask onPreExecute() method and in onPostExecute() method I have passed all data to another Activity and startActivty. Then I dismiss the progress dialog. But, it not fine.
As when the second activity loaded data on UI in onCreate method then ProgressBar hangs.
How do I solve this problem.
Here is my code:
#Override
protected void onPreExecute() {
proDialog = new ProgressDialog(mContext);
proDialog.setTitle("Support Manager");
proDialog.setMessage("Logging in ...");
proDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
proDialog.setIcon(R.drawable.ic_launcher);
proDialog.show();
super.onPreExecute();
}
#Override
protected RepresentativeData doInBackground(String... params) {
JSONObject result = null;
try {
result = client.reprentativeDetailNode(params[0]);
LoginJsonParsing loginJsonParsing = new LoginJsonParsing();
Details = loginJsonParsing
.Details(result);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return Details;
}
#Override
protected void onPostExecute(Data result) {
Intent secActivity = new Intent(mContext,YourRepresentative.class);
secAcitivity.putExtra("detail", result);
mContext.startActivity(secActivity);
proDialog.dismiss();
super.onPostExecute(result);
}
You can't have a progress to be displayed when switching to a new activity
I have an inner class that downloads some images from the server. The problem is that the ProgressDialog does not dismiss() onPostExecute() method and don't understand why.
I understand that the progress dialog should be shown onPreExecute() method, and the after the code from the doInBackground() finished , in the onPostExecute() method the dialog should be dismiss. Do you have any idea what i am doing wrong here? Thank you.
/**
* Download images from server
*/
public class DownloadAsyncTask extends AsyncTask<Void, Integer, Void> {
private ProgressDialog mDialog;
// execution of result of Long time consuming operation
protected void onPostExecute(Void result) {
// progressDialog.show();
if (mDialog.isShowing()) {
mDialog.dismiss();
}
}
// Things to be done before execution of long running operation.
protected void onPreExecute() {
mDialog = ProgressDialog
.show(ImagesActivity.this, getString(R.string.pleasewait),
getString(R.string.loading));
}
// perform long running operation operation
protected Void doInBackground(Void... params) {
System.out.println("doInBackground loading.." + id);
String tempPath = FileUtils.createTempFile(id);
for (int i = 0; i < imagePaths.size(); i++) {
imagePaths.get(i).trim();
try {
Bitmap imgTemp;
imgTemp = FileUtils.downloadBitmapFromURL(id,
imagePaths.get(i), tempPath);
System.out.println("imgTemp: " + imgTemp);
if (imgTemp != null) {
// save image on sdcard.
// compress it for performance
Bitmap img = Bitmap.createScaledBitmap(imgTemp, 90, 80,
true);
imgTemp.recycle();
FileUtils.saveDataToFile(img, tempPath,
imagePaths.get(i));
} else {
continue;
}
} catch (IOException e) {
e.printStackTrace();
mDialog.dismiss();
}
}
Looper.prepare();
mDialog.dismiss();
return null;
}
/*
* Things to be done while execution of long running operation is in
* progress.
*/
protected void onProgressUpdate(Integer... values) {
if (mDialog.isShowing()) {
mDialog.dismiss();
}
}
}
actually what you are trying to do is to access the UI Thread from another thread and that is not possible , in your case you are using AsyncTask class enables proper and easy use of the UI thread without having to manipulate threads and/or handlers. use onPostExecute(Result) to access the UI Thread.
so this should work
protected void onPostExecute(Void result) {
progressDialog.show();
if (mDialog.isShowing()) {
mDialog.dismiss();
}
}
I've struggled with this same problem for quite a while. Here is how I got it solved, take a look at this part of the documentation:
A dialog is always created and displayed as a part of an Activity. You
should normally create dialogs from within your Activity's
onCreateDialog(int) callback method. When you use this callback, the
Android system automatically manages the state of each dialog and
hooks them to the Activity, effectively making it the "owner" of each
dialog
Note: If you decide to create a dialog outside of the onCreateDialog()
method, it will not be attached to an Activity. You can, however,
attach it to an Activity with setOwnerActivity(Activity).
from: http://developer.android.com/guide/topics/ui/dialogs.html#ShowingADialog
This is an example of what you have to set on your activity:
#Override
protected void onPrepareDialog(int id, Dialog dialog)
{
//This doesn't do anything
if (id == DIALOG_PROGRESS_ID) {
((ProgressDialog)dialog).setIndeterminate(true);
}
super.onPrepareDialog(id, dialog);
}
#Override
protected Dialog onCreateDialog(int id)
{
if (id == DIALOG_PROGRESS_ID) {
ProgressDialog dialog = new ProgressDialog(this);
dialog.setMessage("Loading");
dialog.setCancelable(false);
dialog.setIndeterminate(true);
return dialog;
}
return null;
}
You can then call
myActivity.showDialog(myActivity.DIALOG_PROGRESS_ID), myActivity.dismissDialog(myActivity.DIALOG_PROGRESS_ID) from any where as long as you have a reference to your activity instance.
Use a handler and onPostExecute() send the handler msg to dismiss the progress dialog.
You can get help from this link ProgressDialog dismissal in android
Your code is working fine but can you check that control are reaching in Post onPostExecute() method I have tried as
package com.alarm.activity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
public class AlarmManagerActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set up main content view
setContentView(R.layout.main);
new DownloadAsyncTask().execute();
}
/**
* Download images from server
*/
public class DownloadAsyncTask extends AsyncTask<Void, Integer, Void> {
private ProgressDialog mDialog;
// execution of result of Long time consuming operation
#Override
protected void onPostExecute(Void result) {
// progressDialog.show();
if (mDialog.isShowing()) {
mDialog.dismiss();
}
}
// Things to be done before execution of long running operation.
#Override
protected void onPreExecute() {
mDialog = ProgressDialog.show(AlarmManagerActivity.this, "Hello", "Test");
}
// perform long running operation operation
#Override
protected Void doInBackground(Void... params) {
//System.out.println("doInBackground loading.." + id);
/* String tempPath = FileUtils.createTempFile(id);
for (int i = 0; i < imagePaths.size(); i++) {
imagePaths.get(i).trim();
try {
Bitmap imgTemp;
imgTemp = FileUtils.downloadBitmapFromURL(id, imagePaths.get(i), tempPath);
System.out.println("imgTemp: " + imgTemp);
if (imgTemp != null) {
// save image on sdcard.
// compress it for performance
Bitmap img = Bitmap.createScaledBitmap(imgTemp, 90, 80, true);
imgTemp.recycle();
FileUtils.saveDataToFile(img, tempPath, imagePaths.get(i));
}
else {
continue;
}
}
catch (IOException e) {
e.printStackTrace();
mDialog.dismiss();
}
}
Looper.prepare();
mDialog.dismiss();*/
try {
Thread.sleep(5000);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/*
* Things to be done while execution of long running operation is in
* progress.
*/
#Override
protected void onProgressUpdate(Integer... values) {
if (mDialog.isShowing()) {
mDialog.dismiss();
}
}
}
}
I think problem in doInbackground() method. I have simply run thread for sleep 5 sec and after control reaches in post() method and dissmiss progress dialog.
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();
}
}