Using Context in a Fragment

Using context in a fragment

You can use getActivity(), which returns the activity associated with a fragment.

The activity is a context (since Activity extends Context).

best way to use context in fragment

I think the way you are storing the context is really optimal as with that you will be able to use it within each of your sub fragment instances. Because MainActivity is an instance variable in your fragment, it will be garbage collected when your fragment gets destroyed. And if I'm not mistaken about Activity-Fragment lifecycle, when your activity gets rotated, new fragments will be created and the older fragment instances will get destroyed. So, we're good there too. However, you need to be careful with your context variable declaration:

public MainActivity activity;

This makes it accessible from anywhere. Any class can call something like context = fragIns.activity and save it there. This will be really bad for you because now it holds a reference to that context variable. Now, when your fragment is no longer needed it will not be garbage collected because some other class is holding a reference to one of its variable. You'd find yourself in "memory leak town".

Make sure you hold this variable dearly and its reference is not passed to other classes. Since, its in a super class, you may define it as:

protected MainActivity activity;

This should do the job.

How to initialize context in fragment on Android kotlin

I changed your codes with below codes :

class HomeRegisteredFragment : Fragment() {

lateinit var toolbarTile: TextView
lateinit var handler: Handler

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

return inflater.inflate(R.layout.fragment_home_registered, container, false)
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//Initialize
activity?.let {
toolbarTile = it.findViewById(R.id.homePage_toolbarTitle)
}
}

override fun setUserVisibleHint(isVisibleToUser: Boolean) {
super.setUserVisibleHint(isVisibleToUser)
if (isVisibleToUser) {
//Initialize
handler = Handler()
//Set delay
handler.postDelayed({
Toast.makeText(requireContext(),"Show",Toast.LENGTH_SHORT).show()
}, 10)
}
}
}

First you should use requireContext() instead of context() for avoid from memory leak.

For show Toast for every time, you can initialize handler in setUserVisibleHint , then after some delay run your code!

I hope help you

getContext() in Fragment

All the mentioned answers are basically correct. You should get the activity's context between onAttach and onDetach so I like adding this to my fragments:

private Context mContext;

@Override
public void onAttach(Context context) {
super.onAttach(context);
mContext = context;
}

@Override
public void onDetach() {
super.onDetach();
mContext = null;
}

and then whenever I use mContext I add a check:

if(mContext != null) {
//your code that uses Context

}

UPDATE:

In Support Library 27.1.0 and later, Google has introduced new methods requireContext() and requireActivity() that will return a non null Context or Activty.

If the Fragment is not currently attached at the time of calling the method, it will throw an IllegalStateException: so use within a try catch block.

Retrieve Context from a fragment

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.

How to use Context in Fragment using Android Kotlin?

Replace:

  val dbHandler = FilesDatabase(this)

with:

  val dbHandler = FilesDatabase(requireActivity())

Using context of a fragment within its innerclass in Kotlin

In Kotlin, a class must be explicitly declared inner class in order to use fields / methods from the outer class.

How a Fragment can be associated with a Context?

How an Fragment can be associated with a Context?

You must have heard of FragmentHostCallback. If you haven't check out the link.

In a simple way, it is an integration point with a Fragment Host. When I say Fragment Host, It is an object that can hold Fragments. For example an Activity. In order to host a fragment - one must implement FragmentHostCallback.

However, I haven't come up with any ideas about how Fragment can be implemented in non-activity objects. Will see in future may be...

So that way, getActivity() will return null on non-activity objects.

PS,

Always go for getContext() if you are requiring context rather than activity



Related Topics



Leave a reply



Submit