Skip to content
Advertisement

Retrieve Context from a fragment

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

JavaScript

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:

JavaScript

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:

JavaScript

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement