-3

Toast.makeText(MainActivity.this,"YOUR MESSAGE",Toast.LENGTH_LONG).show();

Toast.makeText(getApplicationContext(),String.valueOf(sum),Toast.LENGTH_LONG).show();

why in the above statement MainActivity.this is used and getApplicationcontext() in another one and what do they do?

prashant17
  • 1,520
  • 3
  • 14
  • 23
Dhruv
  • 13
  • 7

1 Answers1

1

There is not much difference as such, Toast.makeText basically needs a Context obj as first parameter. Since deep in the Hierarchy Activity extends Context, passing either activityObj.this or getApplicationContext() should do the trick.

However you need to understand the usage of getApplicationContext() which has key differentiator, based on the documentation for getApplicationContext() :

Return the context of the single, global Application object of the current process. This generally should only be used if you need a Context whose lifecycle is separate from the current context, that is tied to the lifetime of the process rather than the current component.

Where as Activity context is associated with to the activity and can be destroyed if the activity is destroyed -- there may be multiple activities (more than likely) with a single application. You can follow this SO for more details

Sagar
  • 23,903
  • 4
  • 62
  • 62