Usar el contexto en un fragmento


¿Cómo puedo obtener el contexto en un fragmento?

Necesito usar mi base de datos cuyo constructor toma en el contexto, pero getApplicationContext() y FragmentClass.this no funcionan, así que ¿qué puedo hacer?

Constructor de base de datos

public Database(Context ctx)
{
    this.context = ctx;
    DBHelper = new DatabaseHelper(context);
}
Author: Peter Mortensen, 2011-11-21

23 answers

Puede utilizar getActivity(), que devuelve la actividad asociada con un fragmento.
La actividad es un contexto (ya que la actividad extiende el Contexto).

 1174
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-01 09:22:09

Para hacer como la respuesta anterior, puede anular el método onAttach de fragmento:

public static class DummySectionFragment extends Fragment{
...
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        DBHelper = new DatabaseHelper(activity);
    }
}
 117
Author: iambox,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-29 03:47:17

Siempre usa el método getActivity() para obtener el contexto de tu actividad adjunta, pero siempre recuerda una cosa: Los fragmentos son ligeramente inestables y getActivitydevuelve null algunas veces, así que para eso, siempre revisa el método isAdded() de fragment antes de obtener el contexto por getActivity().

 20
Author: Ankur Chaudhary,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-31 17:15:51

La forma más fácil y precisa de obtener el contexto del fragmento que encontré es obtenerlo directamente desde ViewGroup cuando llamas al método onCreateView al menos aquí estás seguro de que no obtendrás null para getActivity():

public class Animal extends Fragment { 
  Context thiscontext;
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
  {
    thiscontext = container.getContext();
 15
Author: Amerdroid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-09 19:44:21
@Override
public void onAttach(Activity activity) {
    // TODO Auto-generated method stub
    super.onAttach(activity);
    context=activity;
}
 9
Author: taran mahal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-17 06:00:58

Para obtener el contexto dentro del Fragmento será posible usar getActivity() :

public Database()
{
    this.context = getActivity();
    DBHelper = new DatabaseHelper(this.context);
}
  • Tenga cuidado, para obtener el Activity asociado con el fragmento usando getActivity(), puede usarlo pero no se recomienda que cause fugas de memoria.

Creo que un enfoque mejor debe ser obtener el Activity del método onAttach():

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    context = activity;
}
 5
Author: Jorgesys,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-02 16:05:35

Otro enfoque alternativo es:

Puedes obtener el contexto usando:

getActivity().getApplicationContext();
 4
Author: codercat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-31 17:16:35

También se puede obtener el contexto del parámetro inflater, cuando se sobrescribe onCreateView.

public static class MyFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
        /* ... */
        Context context = inflater.getContext();
        /* ... */
    }
}
 3
Author: luizfls,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-19 05:39:40

getContext() llegó en API 23. Reemplázalo con getActivity () en todas partes del código.

Vea si corrige el error. Intente usar métodos que estén entre el nivel de API de destino y el nivel mínimo, de lo contrario este error se producirá.

 3
Author: Naveen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-31 17:26:40

Desde el nivel de API 23 existe getContext(), pero si desea admitir versiones anteriores, puede usar getActivity().getApplicationContext() mientras que todavía recomiendo usar la versión de soporte de Fragment que es android.support.v4.app.Fragment.

 3
Author: Androbin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-19 09:57:38

getActivity() es un hijo de Contexto por lo que debería funcionar para usted

 2
Author: qazimusab,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-09 21:37:32

Tienes diferentes opciones:

  • Si tu minSdk getActivity(), ya que esto es un Context.
  • Si tu minSdk es >=23, entonces puedes usar getContext().

Si no necesita soportar versiones antiguas, vaya con getContext().

 2
Author: Jorge,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-01 13:45:46

Para Kotlin puedes usar context directamente en fragmentos. Pero en algunos casos se encuentra un error como

Error de tipo: ¿el tipo inferido es Contexto? pero el contexto se esperaba

Para eso puedes hacer esto

val ctx = context ?: return
textViewABC.setTextColor(ContextCompat.getColor(ctx, android.R.color.black))
 2
Author: KishanSolanki124,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-08 12:41:46

Idealmente, no debería necesitar usar globales. El fragmento tiene diferentes notificaciones, siendo uno de ellos onActivityCreated. Puede obtener la instancia de la actividad en este evento de ciclo de vida del fragmento.

Entonces: puedes desreferenciar el fragmento para obtener activity, context o applicationcontext como desees:

this.getActivity() le dará la manija a la actividad this.getContext() le dará un identificador al contexto this.getActivity().getApplicationContext() le dará el identificador del contexto de la aplicación. Deberías preferiblemente use el contexto de la aplicación cuando lo pase a la base de datos.

 1
Author: user5610809,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-27 05:32:37

La forma sencilla es usar getActivity(). Pero creo que la mayor confusión de usar el método getActivity() para obtener el contexto aquí es una excepción de puntero nulo.

Para esto, primero verifique con el método isAdded() que determinará si se agrega o no, y luego podemos usar el getActivity() para obtener el contexto de la Actividad.

 1
Author: Saubhagya Ranjan Das,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-31 17:24:20

Use fragmentos de Biblioteca de soporte -

android.support.v4.app.Fragment

Y luego anular

void onAttach (Context context) {
  this.context = context;
}

De esta manera puede estar seguro de que el contexto siempre será un valor no nulo.

 1
Author: lomza,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-14 09:32:35

El método getContext() ayuda a usar el Contexto de la clase en una actividad de fragmento.

 0
Author: Gavine Joyce,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-20 07:20:28

Puedes llamar a getActivity() o,

public void onAttach(Context context) {
    super.onAttach(context);
    this.activity = (CashActivity) context;
    this.money = this.activity.money;
}
 0
Author: 蔡健烽,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-01 09:07:54

Creo que puedes usar

public static class MyFragment extends Fragment {
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

      Context context = getActivity.getContext();

  }
}
 0
Author: aswinbhim nath,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-08 09:27:31
public class MenuFragment extends Fragment implements View.OnClickListener {
    private Context mContext;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        FragmentMenuBinding binding=FragmentMenuBinding.inflate(inflater,container,false);
        View view=binding.getRoot();
        mContext=view.getContext();
        return view;
    }
}
 0
Author: Mohsinali,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-03 12:19:20

También puedes usar:

inflater.getContext();

Pero preferiría usar

getActivity()

O

getContext
 0
Author: Deplover,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-15 18:36:44

Necesito contexto para usar ArrayAdapter EN fragment, cuando estaba usando getActivity se produce un error, pero cuando lo reemplazo con getContext funciona para mí

listView LV=getView().findViewById(R.id.listOFsensors);
LV.setAdapter(new ArrayAdapter<String>(getContext(),android.R.layout.simple_list_item_1 ,listSensorType));
 0
Author: ghazaleh javaheri,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-29 12:04:07

Puedes usar getActivity() o getContext en el fragmento.

Documentación

/**
 * Return the {@link FragmentActivity} this fragment is currently associated with.
 * May return {@code null} if the fragment is associated with a {@link Context}
 * instead.
 *
 * @see #requireActivity()
 */
@Nullable
final public FragmentActivity getActivity() {
    return mHost == null ? null : (FragmentActivity) mHost.getActivity();
}

Y

 /**
     * Return the {@link Context} this fragment is currently associated with.
     *
     * @see #requireContext()
     */
    @Nullable
    public Context getContext() {
        return mHost == null ? null : mHost.getContext();
    }

Consejo profesional

Compruebe siempre if(getActivity!=null) porque puede ser null cuando fragment no se adjunta a la actividad. A veces, hacer una operación larga en fragment (como obtener datos de la api rest) lleva algún tiempo. y si el usuario navega a otro fragmento. Entonces getActivity será null. Y obtendrá NPE si no lo manejó.

 0
Author: Khemraj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-19 04:14:57