2

I need context many times in my fragment:

    ...
    account.restore(getContext());
    ...
    dbHelper = new DBHelper(getContext());
    ...
    DiskLruBasedCache.ImageCacheParams cacheParams = new DiskLruBasedCache.ImageCacheParams(getContext(), "CacheDirectory");
    ...
    mImageLoader = new SimpleImageLoader(getContext(), cacheParams);
    ...
    Toast.makeText(getContext(), "err: " + error, Toast.LENGTH_LONG).show();
    ...
    RecyclerView.LayoutManager layoutManager = new CustomLayoutManager(getContext());
    ...

Or should I initialize it once and then use it.

What is best way ?

Kartik Shandilya
  • 3,796
  • 5
  • 24
  • 42
Serg
  • 103
  • 1
  • 9

2 Answers2

2

This is mostly a matter of preference. You can call getContext() wherever you need one -- no cause to be worried about perf overhead. Or you can assign a private Context context field in your onCreate method. Or, if a particular method has multiple uses, create a local variable.

If getContext was potentially slow, then you should definitely have stashed it, but it's really just a simple accessor (almost -- it does one bit of indirection internally).

Go with whatever you find most readable.

Petter Hesselberg
  • 5,062
  • 2
  • 24
  • 42
0

In this case, it would be best to call it once and use it. This is due to the fact that the execution will be faster without the extraneous function calls. It would be common to see

Context context = getContext();

I have done this many times and stored it to a variable in a class. In that case though it looks like this:

class SomeClass {
   Context context;
   @Override
   void onCreate(){
      context = getContext();
   }
}
Andrew Myers
  • 2,754
  • 5
  • 32
  • 40