0

I am having button that laid out in Linear Layout on Activity .

when I clicked on it, an message appear on screen using Toast Class

two methods works fine for me

first one is :

private void DisplayToast(String msg)
{
    Toast.makeText(getBaseContext(), msg,
    Toast.LENGTH_SHORT).show();
}

and the second one is :

private void DisplayToast(String msg)
{
    Toast.makeText(this, msg,
    Toast.LENGTH_SHORT).show();
}

my question is what is the deference between getBaseContext() and this ,and when I should use getBaseContext() and when I should use this ??

ollo
  • 24,797
  • 14
  • 106
  • 155
Mohamad Ghanem
  • 599
  • 2
  • 8
  • 25
  • See here http://stackoverflow.com/questions/9605459/android-why-must-use-getbasecontext-instead-of-this – Alexander Kulyakhtin May 09 '13 at 18:37
  • 2
    short answer is you should basically never be using `getBaseContext()` unless you know exactly why you need to use it ;-) Used incorrectly it is prone to memory leaks, and it is rarely ever actually needed you are normally ok with either `YourActivity.this` or `getApplicationContext()`. – FoamyGuy May 09 '13 at 18:42
  • getBaseContext() is used in special cases.If you are under Activity always preffer using Activity Context i.e this – Vipul May 09 '13 at 18:48
  • Ok thank you all :), but in the above code why two methods are working fine for me and didn't get any errors ??? – Mohamad Ghanem May 09 '13 at 18:56
  • using `getBaseContext()` will not produce any immediately visible errors. But it is unneeded in this situation and _can_ lead to mean memory leaks so it is best to avoid using it unless you understand exactly when and why its needed. – FoamyGuy May 09 '13 at 19:02

1 Answers1

0

Your Activity is a Context, so use it directly with this.

Keep getBaseContext for special cases where your Activity is not reachable directly.

herveRilos
  • 106
  • 1
  • 5