0

i'm not asking diffrence, but how to use these referenes?, Class level object to store their reference or use getter everytime which is provided by super class, Which is a better code practice: 1. call getActivity(), getApplicationContext() ..etc everytime in a local method or pass method as parameter when required in an activity or fragment.

  1. Store their reference in a class level object and use it whereever it's required with null check in an activity or fragment.

I would like to know what is more efficient and why?

type1:

Class A extends Activity
{
  @Override
  public void onCreate()
  {
      methodA(getApplicationContext());
      //or if fragment
      methodA(getActivity());

      Toast.makeText(getApplicationContext(),...).show();
  }

 private void methodA(Context mContext)
 {
   ......
   ......
 }
private void methodA()
 {
   Activity activity = getActivity();
   ......
   ......
 }

}

type2:

class A extends Activity{
private Activity mContext;
private Activity mActRef; //if fragment

@Override
public void onCreate()
{
 mContext = getApplicationContext();
 mActRef = getActivity();//if fragment;
      methodA(mContext);
      //or if fragment
      methodA(mActRef);
   ..........
.........
.........

      Toast.makeText(mContext,...).show();
 }

 private void methodA(Context mContext)
 {
   ......
   ......
 }
private void methodA()
 {
   Toast.makeText(mContext,....).show();
 }

}

}
Jayant Arora
  • 1,241
  • 2
  • 15
  • 24
  • the Activity and the Application Context are used for different purpose. If there was no differences between them we will have get only one. Please refer to the documentation to understand the slightly, but important, difference – Blackbelt Mar 02 '16 at 11:44
  • i'm not asking the difference i'm asking how to use them : using a class level object or using a getter method provided. – Jayant Arora Mar 02 '16 at 11:46
  • `getActivity()` is not a method of `Activity`, btw, if you are in a class that can access directly the context, there is no need to provide methods that take a Context as paramenter. You'll need that only if the method is static – Blackbelt Mar 02 '16 at 11:50
  • http://stackoverflow.com/questions/5018545/getapplication-vs-getapplicationcontext – Fabio Venturi Pastor Mar 02 '16 at 12:33
  • Related - http://stackoverflow.com/questions/4128589/difference-between-activity-context-and-application-context – Sufian Jul 09 '16 at 01:07

1 Answers1

-1

getActivity() and getApplicationContext() both return the context and available throughout the class extend with Activity.

According to my opinion No need to create a global variable for them because they are available at class level. Both are correct but storing the context is not efficient.

Shankar
  • 518
  • 5
  • 16