Iam calling a Asynctask from Scheduled Service Every 10 mins it will Run.
while running the Service, Progress dialog getting Exception from OnpreExecute.
ERROR :
FATAL EXCEPTION: main
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
at android.view.ViewRootImpl.setView(ViewRootImpl.java:594)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:259)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:286)
EDIT 1:
Alarm Manager for calling the service for every 5 mins
/*Alarm manager Service for From Server*/
private void setServerFetch() {
// for to Server to GPS PING
Intent myIntent1 = new Intent(LoginPage.this, AlarmService.class);
pendingintent1 = PendingIntent.getService(LoginPage.this, 1111, myIntent1, 0);
AlarmManager alarmManager5 = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTimeInMillis(System.currentTimeMillis());
calendar1.add(Calendar.SECOND, 1);
alarmManager5.set(AlarmManager.RTC_WAKEUP, calendar1.getTimeInMillis(), pendingintent1);
alarmManager5.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar1.getTimeInMillis(), 300 * 1000, pendingintent1);
}
Calling the AsyncTask from Service Onstart
#Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
try
{
Asynctask_Incident task=new Asynctask_Incident();
task=new();
}
catch (Exception e)
{
e.printStackTrace();
Log.i("PING", "EXCEPTION in reading Data from Web Async task ONstart.!");
}
}
Asynctask Class onStart Method
public class Asynctask_Incident extends AsyncTask<String, Void, Void>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
runOnUiThread(new Runnable() {
#Override
public void run() {
if (!pDialog.isShowing())
{
pDialog = new ProgressDialog(appContext);
pDialog.setCanceledOnTouchOutside(false);
pDialog.setCancelable(false);
pDialog.setMessage("Please Wait Updating Data From...");
pDialog.show();
}
}
});
}
#Override
protected Void doInBackground(String... params)
{
try {
getAPICall();
} catch (Exception e) {
e.printStackTrace();
if (pDialog.isShowing()) {
pDialog.dismiss();
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid)
{
super.onPostExecute(aVoid);
if (pDialog.isShowing()) {
pDialog.dismiss();
}
}
}
Help me to Solve this Issue.
Actually you can't start a progress dialog from a service, because it needs the activity context not application context which come to be null in your case.
More info here:
link1 , link2 and link3
If you want to trigger progress dialog based on service action, you may use Observer design patter, look here.
Update:
If your app is running, you can use Handler and run it each 5 minutes.
Here is a complete example:
public class TestActivity extends AppCompatActivity {
private Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//
new Asynctask_Incident(TestActivity.this).execute("url");
handler.postDelayed(this, 5 * DateUtils.MINUTE_IN_MILLIS);
}
}, 0);
}
public class Asynctask_Incident extends AsyncTask<String, Void, Void> {
ProgressDialog pDialog;
Context appContext;
public Asynctask_Incident(Context ctx) {
appContext = ctx;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(appContext);
pDialog.setCanceledOnTouchOutside(false);
pDialog.setCancelable(false);
pDialog.setMessage("Please Wait Updating Data From...");
pDialog.show();
}
#Override
protected Void doInBackground(String... params) {
try {
getAPICall();
} catch (Exception e) {
e.printStackTrace();
if (pDialog.isShowing()) {
pDialog.dismiss();
}
}
return null;
}
private void getAPICall() {
//5 seconds delay for test, you can put your code here
try {
Thread.sleep(5 * DateUtils.SECOND_IN_MILLIS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (pDialog.isShowing()) {
pDialog.dismiss();
}
}
}
}
Intialize your ProgressDialog.
OnPreExecute();
runOnUiThread(new Runnable() {
#Override
public void run() {
if (pDialog == null)
{
pDialog = new ProgressDialog(appContext);
pDialog.setCanceledOnTouchOutside(false);
pDialog.setCancelable(false);
pDialog.setMessage("Please Wait Updating Data From...");
}
pDialog.show();
}
});
OnPostExecute();
pDialog.dismiss();
The exception Exception:android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application comes when the context is not alive. There may be other reason for this exception but context is major reason. Moreover, if previously shown Dialog is not dismissed, exception may occur.
Please try this code :
runOnUiThread(new Runnable() {
#Override
public void run() {
if(appContext != null) {
// if dialog is already showing, hide it
if(pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
if (pDialog == null) {
pDialog = new ProgressDialog(appContext);
pDialog.setCanceledOnTouchOutside(false);
pDialog.setCancelable(false);
pDialog.setMessage("Please Wait Updating Data From...");
}
pDialog.show();
} else {
Log.e("Error","Context is Null");
}
}
});
An additional check can be added : http://dimitar.me/android-displaying-dialogs-from-background-threads/
You do not need to initialize the dialog in a thread in the onPreExecute. Because this method is always called in the UI thread. By calling a thread you are delaying it. So the doInbackground perhaps happened before the dialog was created.
Also you should not call anything that modifies the UI in the doItBackground method. Because this method runs in a worker thread. Any UI call must be in the main thread. The onPostExecute is called by the main thread. So put your dialog related calls there, but not in the doInBackground.
These lines in the doInbackground need to be removed.
if (pDialog.isShowing()) {
pDialog.dismiss();
}
1) You don't need your ProgressDialog setup inside a Runnable, anything in onPreExecute() and onPostExecute() already runs on the UI thread. Only doInBackground() runs off the UI thread.
2) Put AsyncTask class in MainActivity, call it from MainActivity, not from your Service. Call your AsyncTask from the MainActivity like this:
new MyAsyncTask(MainActivity.this).execute("");
3) Finally, put this constructor in your AsyncTask class:
public MyAsyncTask(Context context) {
appContext = context;
}
It seems like your context does not have the right set of resources.
Make sure that your are using the right context.
Context context = this;
ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.show();
where "this" - AppCompatActivity or Activity context
Related
I have set the IP of Ethernet. here i am creating the file on a specific path and run the code of IP set i.e.,sudo.
Everything works well but It is not showing the progress dialog box on the click of the submit button but all other functions mentioned in the setOnClickListener are working properly.
Can anybody help me.
submt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validationIP();
if (var == true) {
ProgressDialog progressdialog = new ProgressDialog(Third_Ethernet_Layout.this);
progressdialog.setMessage("Please Wait....");
progressdialog.show();
progressdialog.setCancelable(false);
progressdialog.setCanceledOnTouchOutside(false);
try {
File file = new File(filepath);
file.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
write();
sudo(ipfetch, netmaskfetch, gatewayfetch, dns1fetch, dns2fetch);
progressdialog.dismiss();
finish();
Toast.makeText(Third_Ethernet_Layout.this, "Ethernet IP Change Successfully", Toast.LENGTH_SHORT).show();
}
}
});
You are using progressdialog.dismiss(); so that progressdialog is dismissed.
You should user asunc Task for it
private class AsyncAboutUs extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressdialog = new ProgressDialog(Third_Ethernet_Layout.this);
progressdialog.setMessage("Please Wait....");
progressdialog.show();
progressdialog.setCancelable(false);
progressdialog.setCanceledOnTouchOutside(false);
}
#Override
protected Void doInBackground(Void... strings) {
try {
File file = new File(filepath);
file.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
write();
sudo(ipfetch, netmaskfetch, gatewayfetch, dns1fetch, dns2fetch);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (!isCancelled()) {
finish();
}
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
ON Button Click :
submt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validationIP();
if (var == true) {
new AsyncAboutUs().execute();
}
}
});
The code for showing progress dialog is working fine, may be the process is fast and thats why the progress dialog is not visible.
can try using a thread sleep to actually see if there is an issue with it.
It does show the progress but you hide it immediately by calling dismiss() and further by finish().
However, doing your heavy task inside the handler is an incorrect way to achieve what you want. It would not work as you think anyway. What will happen is that your code will block UI thread inside handler and no progress will be shown (and application will potentially be killed if you hold long enough).
The correct way to do this is to implement an AsyncTask, there is a straightforward code example in this documentation link. You need to show() progress dialog, execute the async task, perform your file etc. code in doInBackground() and update progress values by publishProgress on the way.
In the onProgressUpdate(), update the dialog or required fields and, finally, in onPostExecute do the finish() or other actions you wish on completion.
im try to show ProgressDialog in side the thread.but when the app run Progressdialog will crach and it give this Exception
android.view.WindowLeaked:
Activity com.testApp.CaptureSignature has leaked window
com.android.internal.policy.impl.PhoneWindow$DecorView{528dd504
V.E..... R.....I. 0,0-949,480} that was originally added here
error getting when line executing
pDialog.show();
public void syncing(final int sel){
if(sel==1){
ProgressDialo pDialog = new ProgressDialog(CaptureSignature.this);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(false);
pDialog.setProgress(0);
pDialog.setOnDismissListener(new MyCustomDialog.OnDismissListener() {
#Override
public void onDismiss(final DialogInterface dialog) {
doaftersync(pDialog.getProgress(),sel);
}
});
pDialog.setMessage("Syncing Deliveries.Please wait..");
pDialog.show();
Thread background = new Thread (new Runnable() {
public void run() {
progressHandler.sendMessage(progressHandler.obtainMessage());
int stat = deliveryup();
if(stat==1){
try {
locationManager.removeUpdates(locationListner);
} catch (Exception e2) {
}
}else{
pDialog.dismiss();
return;
}
progressHandler.sendMessage(progressHandler.obtainMessage());
int isustat=issueup();
if(isustat==0){
pDialog.dismiss();
return;
}
progressHandler.sendMessage(progressHandler.obtainMessage());
int locstat=locationup();
if(locstat==0){
pDialog.dismiss();
return;
}
cleanup();
progressHandler.sendMessage(progressHandler.obtainMessage());
pDialog.dismiss();
return;
}
});
background.start();
}
}
// handler for the background updating
Handler progressHandler = new Handler() {
public void handleMessage(Message msg) {
pDialog.incrementProgressBy(25);
}
};
Any Help .. !!
Dismiss Your ProgressDialog in Main Thread Using Handler or Using runOnUiThread() Method
Maybe You get exception because Progress dialog is running while Your Activity is destroyed. you should dismiss dialog when Activity is destroyed
Do all your UI actions in a UI thread.
runOnUiThread(new Runnable() {
#Override
public void run() {
pDialog.dismiss();
}
});
I think the safe way :
if(dialog.isShowing()){
dialog.dismiss();
}
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)
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.
I have a method in my activity to download a set of files. This downloading is taking place when I start a new activity. I have used threads, because it downloads completely whereas AsyncTask may sometimes fail to download all files, it may get stuck in between.
Now, a black screen is shown when the downloading takes place. I want to show it within a ProgressDialog so that user may feel that something is getting downloaded.
I have added a ProgressDialog, but its not showing. Can anyone tell where did I go wrong?
Below is my code:
Inside onCreate() I have written:
downloadFiles();
private boolean downloadFiles() {
showProgressDialog();
for(int i = 0; i < filesList.size();i++) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
//downloading code
});
thread.start();
thread.run();
}
dismissProgressDialog();
return true;
}
//ProgressDialog progressDialog; I have declared earlier.
private void showProgressDialog() {
progressDialog = new ProgressDialog(N12ReadScreenActivity.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setMessage("Downloading files...");
progressDialog.show();
}
private void dismissProgressDialog() {
if(progressDialog != null)
progressDialog.dismiss();
}
Try this .. it's simple
ProgressDialog progress = new ProgressDialog(this);
progress.Indeterminate = true;
progress.SetProgressStyle(ProgressDialogStyle.Spinner);
progress.SetMessage("Downloading Files...");
progress.SetCancelable(false);
RunOnUiThread(() =>
{
progress.Show();
});
Task.Run(()=>
//downloading code here...
).ContinueWith(Result=>RunOnUiThread(()=>progress.Hide()));
Please try Below Code .
private Handler responseHandler=null;
downloadFiles();
private boolean downloadFiles() {
showProgressDialog();
for(int i = 0; i < filesList.size();i++) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
//downloading code
responseHandler.sendEmptyMessage(0);
});
thread.start();
}
responseHandler = new Handler()
{
public void handleMessage(Message msg)
{
super.handleMessage(msg);
try
{
dismissProgressDialog()
}
catch (Exception e)
{
e.printStackTrace();
}
}
};
}
Here in this code when ever your dowload will completed it called response handler and your progress dialog will dismiss.
In downloadFiles() you show the dialog, then start a number of threads and after they've been started the dialog got dismissed. I don't think this is what you want as the dialog gets closed right after the last thread is started and not after the last thread has finished.
The dismissProgressDialog() method must be called after the last thread has finished its work. So at the end of the code run in the thread you have to check whether other threads are still running or whether you can dismiss the dialog as no other threads are running.
Try the following code and let me know how it goes:
private Handler mHandler = new Handler(){
public void handleMessage(Message msg)
{
dismissProgressDialog()
}
};
private boolean downloadFiles() {
showProgressDialog();
for(int i = 0; i < filesList.size();i++) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
//downloading code
});
thread.start();
thread.run();
}
mHandler.sendEmptyMessage(0);
return true;
}
//ProgressDialog progressDialog; I have declared earlier.
private void showProgressDialog() {
progressDialog = new ProgressDialog(N12ReadScreenActivity.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setMessage("Downloading files...");
progressDialog.show();
}
private void dismissProgressDialog() {
if(progressDialog != null)
progressDialog.dismiss();
}