Android: ProgressDialog.show() crashes with getApplicationContext Android: ProgressDialog.show() crashes with getApplicationContext android android

Android: ProgressDialog.show() crashes with getApplicationContext


I am using Android version 2.1 with API Level 7. I faced with this (or similar) problem and solved by using this:

Dialog dialog = new Dialog(this);

instead of this:

Dialog dialog = new Dialog(getApplicationContext());

Hope this helps :)


For me worked changing

builder = new AlertDialog.Builder(getApplicationContext());

to

builder = new AlertDialog.Builder(ThisActivityClassName.this);

Weird thing is that the first one can be found in google tutorial and people get error on this..


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:

@Overridepublic 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}