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.
Related
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
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 want to use a progress dialog in an activity named myActivity.
I launch it from a method in the activity:
progressDialog = ProgressDialog.show(myActivity.this, "", "loading ...");
but nothing appears. Why?
I've also tried this line:
progressDialog = ProgressDialog.show(myActivity.this, "", "loading ...",true);
with the same result.
Just this
//Declare progressDialog before so you can use .hide() later!
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
Please add runnable thread into your code
Example: https://abhiandroid.com/ui/progressdialog
or see this example code
progressDialog.show(); // Display Progress Dialog
progressDialog.setCancelable(false);
new Thread(new Runnable() {
#Override
public void run() {
try {
while (progressDialog.getProgress() <= progressDialog.getMax()) {
Thread.sleep(200);
handle.sendMessage(handle.obtainMessage());
if (progressDialog.getProgress() == progressDialog.getMax()) {
progressDialog.dismiss();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}}).start();
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.
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