Android: Progressdialog.Show() Crashes with Getapplicationcontext

Android: ProgressDialog.show() crashes with getApplicationContext

Which API version are you using? If I'm right about what the problem is then this was fixed in Android 1.6 (API version 4).

It looks like the object reference that getApplicationContext() is returning just points to null. I think you're having a problem similar to one I had in that some of the code in the onCreate() is being run before the window is actually done being built. This is going to be a hack, but try launching a new Thread in a few hundred milliseconds (IIRC: 300-400 seemed to work for me, but you'll need to tinker) that opens your ProgressDialog and starts anything else you needed (eg. network IO). Something like this:

@Override
public void onCreate(Bundle savedInstanceState) {
// do all your other stuff here

new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mProgressDialog = ProgressDialog.show(
YouTube.this.getApplicationContext(), "",
YouTube.this.getString(R.string.loading), true);

// start time consuming background process here
}
}, 1000); // starting it in 1 second
}

App crashes on showing ProgressDialog in non-activity

Pass context parameter in ProgressDialog,So Change

startDialog = new ProgressDialog(this);

to

startDialog = new ProgressDialog(context);

And in your mainActivity change

context = getApplicationContext();

to

context = MainActivty.this;

progressDialog app crashes on screen rotation

That is because of dialog will became null.
You can resolve these using two different ways.

  1. Stop recreating whole activity. i.e setting
    You can avoid activity recreation by adding following to your application's manifest file.

    android:configChanges="orientation|keyboardHidden|screenSize"
    As follows

    <activity
    android:name=".your activity"
    android:configChanges="orientation|keyboardHidden|screenSize"
    android:label="@string/app_name" >
    </activity>
  2. Show/dismiss the dialog within AsyncTask during onPreExecute/onPostExecute as usual, though in case of orientation-change create/show a new instance of the dialog in the activity and pass its reference to the task. Refer below code and do necessary steps.

public class MainActivity extends Activity {

    private Button mButton;
private MyTask mTask = null;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

MyTask task = (MyTask) getLastNonConfigurationInstance();
if (task != null) {
mTask = task;
mTask.mContext = this;
mTask.mDialog = new ProgressDialog(MainActivityProgress.this);
mTask.mDialog.setMessage("Please wait...");
mTask.mDialog.setIndeterminate(false);
mTask.mDialog.setMax(100);
mTask.mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mTask.mDialog.setCancelable(true);
mTask.mDialog.show();
}

mButton = (Button) findViewById(R.id.button1);
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mTask = new MyTask(MainActivity.this);
mTask.execute();
}
});
}

@Override
public Object onRetainNonConfigurationInstance() {
String str = "null";
if (mTask != null) {
str = mTask.toString();
mTask.mDialog.dismiss();
}
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
return mTask;
}

private class MyTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog mDialog;
private MainActivity mContext;

public MyTask(MainActivity context) {
super();
mContext = context;
}

protected void onPreExecute() {
mDialog = new ProgressDialog(MainActivityProgress.this);
mDialog.setMessage("Please wait...");
mDialog.setIndeterminate(false);
mDialog.setMax(100);
mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mDialog.setCancelable(true);
mDialog.show();
}

protected void onPostExecute(Void result) {
mContext.mTask = null;
mDialog.dismiss();
}

@Override
protected Void doInBackground(Void... params) {
SystemClock.sleep(5000);
return null;
}
}
}

Ok, So after editing your code it will look as below:

public class MainActivityProgress extends Activity {

Button button;

public static final int progress_bar_type = 0;

private static String file_url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
private DownloadFileFromURL mTask = null;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity_progress);
button = (Button) findViewById(R.id.btn_download);
DownloadFileFromURL task = (DownloadFileFromURL) getLastNonConfigurationInstance();
if (task != null) {
mTask = task;
mTask.mContext = this;
mTask.mDialog = ProgressDialog.show(MainActivityProgress.this,
"Downloading file.", "Please wait...", true);
}

button.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
mTask = new DownloadFileFromURL(MainActivityProgress.this);
mTask.execute(file_url);
}
});
}

@Override
public Object onRetainNonConfigurationInstance() {
String str = "null";
if (mTask != null) {
str = mTask.toString();
mTask.mDialog.dismiss();
}
return mTask;
}

class DownloadFileFromURL extends AsyncTask<String, String, String> {

private ProgressDialog mDialog;
private MainActivityProgress mContext;

public DownloadFileFromURL(MainActivityProgress context) {
mContext = context;
}

protected void onPreExecute() {
mDialog = ProgressDialog.show(MainActivityProgress.this,
"Downloading file.", "Please wait...", true);
}

@Override
protected String doInBackground(String... f_url) {
SystemClock.sleep(5000);
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();

int lenghtOfFile = conection.getContentLength();

InputStream input = new BufferedInputStream(url.openStream(),
8192);

OutputStream output = new FileOutputStream(
"/sdcard/downloadedfile.jpg");

byte data[] = new byte[1024];

long total = 0;

while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (total * 100) / lenghtOfFile);

output.write(data, 0, count);
}

output.flush();

output.close();
input.close();

} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}

return null;
}
protected void onProgressUpdate(String... progress) {
mDialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String file_url) {
mContext.mTask = null;
if (mDialog.isShowing()) {
mDialog.dismiss();
}

String imagePath = Environment.getExternalStorageDirectory()
.toString() + "/downloadedfile.jpg";
Log.e("imagePath: ", imagePath);
// imageView.setImageDrawable(Drawable.createFromPath(imagePath));
}

}

}

App crashes when using ProgressDialog within AsyncTask

As far as I can see from your code, you're trying to update your UI in the doInBackground method. doInBackground runs in a worker thread and in android you can update the UI only in the main thread. Do your long time job in the doInBackground method but update your UI in a main thread method, like for example onProgressUpdate or onPostExecute. More info about asynctask here

ProgressDialog in AsyncTask throws an exception

ProgressDialog dialog;
@Override
protected void onPreExecute() {
dialog = new ProgressDialog(viewContacts.this);
dialog.setMessage(getString(R.string.please_wait_while_loading));
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}

ProgressDialog crash in fragment after first run

I think you create a fragment inside an activity on which you call finish() before you show the dialog. Try to not call finish() in your if (!isIntroShown()) statement.

From the intro/tutorial you can return to the same created activity later without killing it in the first place.

Android App Crashing whenever progressDialog is canceled

So i got time to do this today - Your AsyncTask should look something like this.

/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
//pDialog = new ProgressDialog(CancelAsyncTask.this);
//pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.home_img));
//pDialog.setMessage("we don dey reach...");
//pDialog.setIndeterminate(true);
//pDialog.setCancelable(true);
//pDialog.setCanceledOnTouchOutside(true);
//pDialog.show();

pDialog = ProgressDialog.show(
CancelAsyncTaskActivity.this,
"Title",
"we don dey reach...",
true,
true,
new DialogInterface.OnCancelListener(){
@Override
public void onCancel(DialogInterface dialog) {
// cancel the AsyncTask here!
mAsyncTask.cancel(true);
}
}
);

}

/**
* getting results from url
* */
protected String doInBackground(String... args) {

// Do your background stuff here

return null;
}

/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting results
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
}
});

}

}

progressdialog crash in AsyncTask class

I ran your code and came to conclusion that you are using a Context like getApplicationContext() instead of an Activity context.

Note that this is the same Context which is passed to Toast.makeText().

Show Progress Dialog between threads?

You should avoid using the getApplicationContext()-method to get a Context-object. There are better ways:

  • If in an Activity, you can simply supply this
  • If in an inner-class of an Activity, you can supply OuterClassName.this
  • When in a Helper-class which needs a Context-object to create e.g. a View, supply a Context-Object via the constructor and save it in a property.

Also see this similar question: Android: ProgressDialog.show() crashes with getApplicationContext



Related Topics



Leave a reply



Submit