Retrieve Context from a fragment

倖福魔咒の 提交于 2019-11-28 21:22:24

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.

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:

@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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!