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 ;
Related
I am trying to use a AlertDialog in Android which will notify the users that they are runing in offline mode after checking the internet connection.
I have used the following codes:
protected Void doInBackground(Void... params) {
if (this.isOnline()) {
new GetJson().execute();
} else {
AlertDialog.Builder builder1 = new AlertDialog.Builder(homeFragment);
builder1.setMessage("INTERNET CONNECTION NOT AVAILABLE. Now you are viewing the news in Offline Mode.");
builder1.setCancelable(true);
AlertDialog alert1 = builder1.create();
alert1.show();
try {
saveFile = new SaveIntoFile(fileName);
jsonStr = saveFile.read();
// Log.d(TAG,"offline data reading from a file");
if (!jsonStr.equals(null))
new GetDatas().execute();
else {
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
But I am getting the error on adding the codes for AlertDialog. The app works fine without the codes for AlertDialog.
What can be the mistakes with this code and how can i correct it to work well??
doInBackground() runs on a separate thread, other than the main thread. You can use UI elements only on main thread. Try using runOnUiThread() method inside doInBackground() to show the dialog.
here AlertDialog will not work, you can use
System.out.println("some text");
if you are using alert just for testing purpose.
otherwise you have to set into a parameter and what ever text you want to put in alertbox and just use it in main thread.
if you have any confusion please let me know .
In Android you can do UI operations only in main thread. So you can show dialog in onPostExecute method. Example:
class anyClassName extends AsyncTask<String,String,String>{
/* uses worker thread */
protected String doInBackground(Void... params) {
if (this.isOnline()) {
new GetJson().execute();
} else { return null }
// ... rest of your code
return ""
}
/* uses main thread*/
protected void onPostExecute(String result){
if(result == null ){
AlertDialog.Builder builder1 = new AlertDialog.Builder(homeFragment);
builder1.setMessage("INTERNET CONNECTION NOT AVAILABLE. Now you are viewing the news in Offline Mode.");
builder1.setCancelable(true);
AlertDialog alert1 = builder1.create();
alert1.show();
}
}
}
class myAsync extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
if(yourWorkIsDone){
return new String("done");
}else{
return new String("Error message");
}
//BUT, if you'd like to check and update user on the error and keep trying then this way
// use just one of these two examples
if(yourWorkIsDone){
// definately is done but hey it depends on you
publishProgress(new String("done"));
}else{
// this is when you have error and wona let the user know about and keep trying to hit it right
publishProgress(new String("error message"));
}
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// here your task is done
// you can put myAlertDialogToShow(Context context,String message) depending on ur choice
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected void onProgressUpdate(String... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
// here your task is running but you are just informing user, runs on the ui..
// you can put myAlertDialogToShow(Context context,String message) depending on ur choice
}
}
void myAlertDialogToShow(Context context,String message){
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setMessage(message);
builder1.setCancelable(true);
AlertDialog alert1 = builder1.create();
alert1.show();
}
ayt..check for silly errors and spellings.. im tired
what i have is two asynctask each one call a function to parse some data ... and i want the asynctask starts after asynctasknew finish how can i do this??? here is my code ..
send.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AsyncCallWS task = new AsyncCallWS();
try{
Intent newintent = getIntent();
mixlist=newintent.getStringArrayListExtra("listmix");
Log.e("listmix",mixlist+"");
for(int i=0;i<=mixlist.size();i++){
if(i==mixlist.size()){
Log.d("states","finished");
Item_Name="0";
Item_Price="0";
Item_Quantity="0";
Total_Price="0";
Customer_Name=name.getText().toString();
Log.e("customer_name",Customer_Name);
Customer_Number=mobile.getText().toString();
Customer_Address=addressnew.getText().toString();
//Call execute
task.execute();
}
else{
Item_Name=mixlist.get(i);
i++;
Item_Price=mixlist.get(i);
i++;
Item_Quantity=mixlist.get(i);
i++;
Total_Price=mixlist.get(i);
Customer_Name="0";
Customer_Number="0";
Customer_Address="0";
// AsyncCallWSnew tasknew = new AsyncCallWSnew();
//Call execute
AsyncCallWSnew tasknew = new AsyncCallWSnew();
tasknew.execute();
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
});
}
private class AsyncCallWS extends AsyncTask<Void, Void, Void> {
protected void onPostExecute(Void result) {
//Make Progress Bar invisible
Toast.makeText(getApplicationContext(), "order has been sent + item price", Toast.LENGTH_LONG).show();
Intent intObj = new Intent(PersonalInfo.this,MainActivity.class);
startActivity(intObj);
//Error status is false
}
//Make Progress Bar visible
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
loginStatus = WebService.invokeLoginWS(Item_Name,Item_Price,Item_Quantity, Total_Price, Customer_Name,
Customer_Number, Customer_Address,"InsertData");
return null;
}
}
private class AsyncCallWSnew extends AsyncTask<Void, Void, Void> {
protected void onPostExecute(Void result) {
//Make Progress Bar invisible
Toast.makeText(getApplicationContext(), "order has been sent", Toast.LENGTH_LONG).show();
Intent intObj = new Intent(PersonalInfo.this,MainActivity.class);
startActivity(intObj);
//Error status is false
}
//Make Progress Bar visible
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
loginStatus = WebService.invokeLoginWS(Item_Name,Item_Price,Item_Quantity, Total_Price, Customer_Name,
Customer_Number, Customer_Address,"InsertData");
return null;
}
}
}
when i make a debug my code works just fine .. but in normal run .. it doesn't can any help me?
There are basically two possibilities:
Simply start the next AsyncTask from onPostExecute() of the previous one
Use AsyncTask.executeOnExecutor() with SerialExecutor and start all of them in a row.
Hi You can use AsyncTask executeonExecutor method to start the async task. But it will require minimum API version 11. Kindly refer the following code.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
new YourFirstTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,params...);
new YourSecondTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,params...);
}else{
new YourFirstTask().execute(params...);
new YourSecondTask().execute(params...);
}
For Lower version you can call directly. automatically system will process one by one.
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
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();
}
}