8

Sorry for my newbie Question, i just cannot find the answer from google and stackoverflow.. i just start learning for android, wish can build a good base for android knowledge. I wondering which i should use in the following if i create toast.maketext in fragment. getActivity() or getAcitivity().getApplicationContext()?

i did try both, it works well..

btn1.setOnClickListener(new View.OnClickListener() {            
@Override
public void onClick(View v) {
 Toast.makeText(getActivity(), "hello",Toast.LENGTH_LONG).show();
 Toast.makeText(getActivity().getApplicationContext(),"Hello",Toast.LENGTH_LONG).show();
}
});
NaiveBz
  • 834
  • 2
  • 8
  • 19

1 Answers1

12

For user interface related calls use the Activity context.

See this explanation by Reto Meier: https://stackoverflow.com/a/987503/534471

Community
  • 1
  • 1
Emanuel Moecklin
  • 28,488
  • 11
  • 69
  • 85
  • so use getActivity() instead of getAcitivity().getApplicationContext() to avoid memory leaks? am i right? please correct me~ – NaiveBz Feb 22 '13 at 02:50
  • 3
    No. As a rule of thumb use the Activity context whenever you are within the scope of an Activity. Use the Application context when you leave the scope of the Activity. I'm aware that this answer might be confusing but the question doesn't have a clear answer and depends a lot on the circumstances. In certain cases you have to use the Activity context or you will get exceptions, in others you should use the Application context to avoid leaking the Activity context. I'm assuming that your code is within an Activity? If yes then use the activity context. If not then please post some more code. – Emanuel Moecklin Feb 22 '13 at 03:21
  • Thanks for your fast replied. erm, how only consider is within the scope of an Activity or leave the scope of Activity? the toast is created inside the fragment Class onCreateView function. is that consider out of scope of Activity? – NaiveBz Feb 22 '13 at 03:39
  • 2
    If it's a Fragment use getActivity() as Context. Just make sure the call happens between onAttach(Activity activity) and onDetach() otherwise there's no Activity attached and you'll get an Exception. – Emanuel Moecklin Feb 22 '13 at 03:52
  • Appreciate for your replied. thanks ~ can you provide me some of useful example and link which case is out of scope Activity? – NaiveBz Feb 22 '13 at 03:58
  • That question has already been discussed on SO: http://stackoverflow.com/q/7298731/534471 http://stackoverflow.com/q/4128589/534471 http://stackoverflow.com/a/987503/534471 It's a confusing topic for a beginner but I can't give you more insight than you'll get from the various SO posts. – Emanuel Moecklin Feb 22 '13 at 04:07
  • ya, that is really confuse and trouble me... until now i not even really understood the purpose of getActivity and getContext.. i think need some time to digest it.. thanks for listed all the useful link for me .. really appreciate.. thanks bro! – NaiveBz Feb 22 '13 at 04:26