20

I created a class to retrieve comments from a JSON encoding from a PHP file. This class, extends from AsyncTask:

public class RecuperarComentarisFoto extends AsyncTask<String, String, String>{

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(????);
        pDialog.setMessage("Creating Product..");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
    }

}

As you can see, I'm trying to show a ProgressDialog while the "doInBackground" proccess is working. But progressDialog constructor, asks for a Context, and I don't know how to provide it.

I'm calling this class from a Fragment, so I can't access the context like this:

pDialog = new ProgressDialog(MyFragmentA.context);

The "main" acitivity is called: AndroidViewPagerActivity which extends FragmentActivity.

(By main, I mean that it's the one that is creating the tabs, and managing the navigation between them.)

This is it's code:

public class AndroidViewPagerActivity extends FragmentActivity {
ViewPager mViewPager;
TabsAdapter mTabsAdapter;


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mViewPager = new ViewPager(this);
    mViewPager.setId(R.id.pager);
    setContentView(mViewPager);

    final ActionBar bar = getActionBar();
    bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_HOME);
    bar.hide();

    mTabsAdapter = new TabsAdapter(this, mViewPager);
    mTabsAdapter.addTab(bar.newTab().setText("Fragment A"), MyFragmentA.class, null);

    if (savedInstanceState != null) {
        bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
    }

}

How can I access the context? Which context should I use? "AndroidViewPagerActivity" context? So how can I access its context from a fragment?

Thank you.

Sergi

5 Answers 5

49

Use getActivity() inside the Fragment to obtain a Context that you can pass along. That works, as Activity inherits from Context.

As alternative you can use getApplicationContext() to obtain the Context.

2
  • Ok, this solved the problem. With your help and some extra googleing, i got it :D. Going to put my final code, so every1 can see the answer implemented.
    – Reinherd
    Jan 4, 2013 at 18:14
  • 3
    Calling getActivity() inside the fragment may result in NullPointerException when used in large scale for some devices. This happens when the call is made before the fragment gets attached to the activity. It also results in memory leaks which can be fatal and hard to find. Go through this to get a better understanding. android-developers.googleblog.com/2009/01/…
    – sid_09
    Mar 20, 2017 at 6:42
3

@heiko-rupp's answer is outdated, Fragment.getContext() has been introduced in Fragments in API 23.

To pass it around from fragment you have to use, like this.getContext()

https://developer.android.com/reference/android/app/Fragment.html#getContext() which according to documentations just

Return the Context this fragment is currently associated with.

1
  • so it won't work in lower apis then and using applicationcontext is better Jan 22, 2019 at 8:07
1

Okay, now I know something new:

  • You've to get the context from the class that instanced the fragment.

You do this by including this in your code in the fragment ("the child").

Context cont;
cont=getActivity();

So then, once you've the context, you pass it. In my case, I had to pass it a AsyncTask class, so I can show a dialog.

new RecuperarComentarisFoto(cont).execute();

And to finish this, on the "RecuperarComentarisFoto" class, I created a constructor. As I've read, it's ok to do it this way.

private Context mContext;
public RecuperarComentarisFoto(Context context){
    this.mContext=context;
}

And the magic:

@Override
protected void onPreExecute() {
    super.onPreExecute();
    ProgressDialog pDialog = new ProgressDialog(this.mContext);
    pDialog.setMessage("Creating Product..");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(true);
    pDialog.show();
}

This all ends with: enter image description here

1

A great way without using getActivity() is creating a local nullable variable inside the fragment

Kotlin

private var attachedContext: Context? = null 

Then in onAttach you correspond the current context to the fragment

 override fun onAttach(context: Context) {
        super.onAttach(context)

        attachedContext = context
}

Lastly when you use it you can check if that context is null, if not you can proceed

attachedContext?.let { safeContext -> 
 
  // Safe place that you know context is not null

}

As a next step, I have placed the debugger so you can see that the context attached to this variable is the same one as getActivity() but the fragments get the context of the parent activity is being contained on

enter image description here

This is a better way to be cleaner in our fragments and explicitly know where the context is coming from with the lifecycle.

0

FragmentActivity this will give you context of activity and then you can pass it to your AsyncTask.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.