New Intent - requireActivity() and requireContext() - android

What is the difference between requireActivity() and requireContext() when starting a new Activity Intent
startActivity(Intent(requireContext(), A::class.java))
startActivity(Intent(requireActivity(), B::class.java))

A Fragment theoretically can be attached to a Context that is not an Activity. In this case requireActivity() would throw an Exception when requireContext() wouldn't.
You would know if you were using a Fragment in this unconventional way, so for all intents and purposes, there is no practical difference.
requireContext() is returning the same Activity instance as requireActivity() would, but it is upcast to Context. An Activity would be implicitly upcast to Context anyway when you pass it to the Intent constructor, since it is expecting a Context.

requireActivity() a method that returns the non-null activity instance to fragment or throws an exception. If you are 100% sure that in your fragment's lifecycle, activity is not null
requireContext() returns a nonnull Context , or throws an exception when one isn't available.

Related

is this good way to access getContext() | requireContext() method each time in Fragment?

I generally prefer to use one Context object and assign value by using getContext() or requireContext() method only once while initializing object inside any Fragment.
I just wanted to know that is this right approach and it utilize less resource for better coding?
Another approach is to use getContext() or requireContext() each time while required inside any Fragment.
Let me attach one of my code snippet.
private lateinit var mContext: Context // Declaring lateinit context
...
...
mContext = requireContext() // Initialization of lateinit context
Thanks in advance.
Your context lives as long as the fragment lives. Therefore, the call to the requireContext() always returns the context instance of the current fragment. Answering your question - using the requireContext() is the most correct way to refer to the context.
There is one more requireActivity() method, that is needed to get the activity of this fragment.
Be careful when creating references to objects returned by these methods.
For example,
private val context = requireContext()
creating such a reference in a instance of a class that is outside of your fragment will lead to a memory leak.
If you still need to pass the context inside any class outside the fragment, then use WeakReference or applicationContext to prevent a memory leak.

use requireActivity() or getActivity() in fragment

When to use the getActivity() in the fragment and when of requireActivity()
Is it better to use a requireActivity() instead of a getActivity()?
In fact, I want to avoid Null error
I use Java
You can use requireActivity() inside the scope of a fragment lifecycle. Inside fragment lifecycle, i.e. between onAttach() and onDetach(), you are sure that the activity is not null. But in case you are not sure the activity is non-null, i.e. inside a thread or callback, it's better to use getActivity() with null check

Should I use getApplicationContext() or getContext() in Intent?

On button click I'm starting a new activity like this:
Intent(requireContext(), SecondActivity::class.java).apply {
putExtra(RECORDED_SUCCESSFULLY, filePath)
(activity as FirstActivity).finish()
startActivity(this)
}
But because I need to finish this activity before creating a new one, requireContext() here will be occasionally equal null and this causes a crash. So my question is, can I use getApplicationContext() or should I use safe call with getContext() in this situation?
It's prefered to use Activityname.this or getApplicationContext().
Remember there are two types of contexts in android and when you are dealing with activity components such as finish use Activityname.this

Problem to get Context in FragmentView Kotlin

I need to get a Context from my activity. When i do that using:
override fun getContext(): Context {
return activity.applicationContext
}
i got:
safe ( .) or non-null asserted ( .) calls are allowed on a nullable receiver of type FragmentACtivity
For formality purposes, posting answer here
activity is calling your fragment's getActivity() which isn't guaranteed to not be null. So you'll have to do activity!!.applicationContext!!
There are scenarios in the life cycle of Android where the activity will be null during the instance of your Fragment. More often than not, activity will exist, but in this case Kotlin is forcing you to be smart about accessing it. A simple (but helpful) nuance of Kotlin

What is different between getContext and getActivity from Fragment in support library?

What is different between getContext() and getActivity() from Fragment in support library?
Do they always return the same object? (activity associated with current fragment)
In most cases there is no difference but ...
So originally Fragments were hosted in FragmentsActivity and back then to get Context one called getActivity().
Just checked the sources and Fragments now can be hosted by anyone implementing FragmentHostCallback interface. And this changed in Support Library version 23, I think.
When using newer version of Support Library, when Fragment is not hosted by an Activity you can get different objects when calling getActivity() and getContext().
When you call getActivity() you get an Activity which is a Context as well.
But when you call getContext you will get a Context which might not be an Activity.
So far, the only provided implementation of FragmentHostCallback (in the OS and the support library) always returns the same value for both getContext() and getActivity().
However, the other constructors of FragmentHostCallback suggest that in future implementations, we may get:
A null Activity and a non-null Context which is not an Activity. This looks improbable but we can imagine that fragments could be used outside Activities in the future, or be fully sandboxed.
A non-null Activity and a non-null Context which is not the same instance as the Activity. For example, Context could be a ContextThemeWrapper.
Conclusion: when you can, use getContext(). When you need Activity-specific calls, use getActivity().
Activity is a subclass of Context. Activity has also Window elements and access to UI methods, Context doesn't. However, in the majority of the cases, it's the same if you need only the Context.
getContext():- Returns the context the view is currently running in. Usually the currently active Activity. getContext() is not defined in an Activity. It's used in a View (or View subclass) to get a reference to the enclosing context (an Activity).
getActivity():- This method gives the context of the Activity. You can use it is like the yourActivity.this. getActivity() is normally used in fragments to get the context of the activity in which they are inserted or inflated.
getContext() - Returns the context view only current running activity.
getActivity()- Return the Activity this fragment is currently associated with.
getActivity() can be used in a Fragment for getting the parent Activity of the Fragment .
You can use getActivity(), which returns the activity associated with a fragment. The activity is a context (since Activity extends Context).
getActivity() can return null if it is called before onAttach of the respective fragment. Context provides information about the Actvity or Application to newly created components. Relevant Context should be provided to newly created components (whether application context or activity context). Since Activity is a subclass of Context, one can use this to get that activity's context.
getContext() Returns the context view only current running activity.
getContext() :
Returns the context view only current running activity.
getActivity():
Return the Activity this fragment is currently associated with.
/**
* Return the {#link Context} this fragment is currently associated with.
*/
public Context getContext() {
return mHost == null ? null : mHost.getContext();
}
/**
* Return the {#link FragmentActivity} this fragment is currently associated with.
* May return {#code null} if the fragment is associated with a {#link Context}
* instead.
*/
final public FragmentActivity getActivity() {
return mHost == null ? null : (FragmentActivity) mHost.getActivity();
}
from source code, we can find that when a fragment is attached to an Activity, getContext returns null. While getActivity returns null when a fragment is attached to context instead

Categories

Resources