0

I am new to Android and may be what i am asking is very silly one..so please forgive me

To create AlertDialog.... standard way is to call

AlertDialog alertDialog = new AlertDialog.Builder(Context here....).create();

then
alertDialog.show();

But i tried via 3 ways...

way 1

AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();

way 2

AlertDialog alertDialog = new AlertDialog.Builder(this).create();

way 3

AlertDialog alertDialog = new AlertDialog.Builder(this.getApplicationContext()).create();

First 2 works fine but 3rd one gives illegalSTateException......

so my query is why it is giving that????

Thanks

Rohit Singhal
  • 381
  • 1
  • 4
  • 22

1 Answers1

2

This question's answer will help you understand the different types of contexts in android

Difference between getContext() , getApplicationContext() , getBaseContext() and "this"

Related to your error, android probably don't want your AlertDialog to be tied to the entire app context, but just to the activity's.

Community
  • 1
  • 1
Robert Estivill
  • 12,369
  • 8
  • 43
  • 64
  • Let me write what i have understood is this... this/ MainActivity.this ====> it get context wrt to Activity which is required But by using getApplicationContext()....it is getting context in which application is running ..which is not required... – Rohit Singhal Feb 04 '13 at 18:15
  • 1
    Activity extends ContextWrapper, therefore getContext(), this and Activity.this are the same reference. getApplicationContext as the docs says ( http://developer.android.com/reference/android/content/ContextWrapper.html#getApplicationContext%28%29 ) is tied to the application process, instead of the current component, in your case, your activity. – Robert Estivill Feb 04 '13 at 18:43