How do I use getActivity
or activity
in other functions outside of onCreate View
, when I use activity in oncreateview or other functions it returns null. in a fragment.
Is there a way to store activity
and use it as a variable in a function outside of oncreateview?
There are answers for this in java but I couldn’t find in Kotlin, (interchanging between them is a bit confusing)
This is onCreateView
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
var mActivity = activity. // This returned Null
phRecycler = view?.findViewById(R.id.recyle)
E_shelf = view?.findViewById(R.id.E_shelf)
phoneRecycler()
return inflater.inflate(R.layout.fragment_home3, container, false)
}
this is another function in the same fragment
fun phoneRecycler() {
//All Gradients
//HSSFSheet sheet = readExcel();
val TAG = "Main"
val myMap: MutableMap<String, Int> = HashMap()
myMap["Index"] = 0
val LatestShelf = ArrayList<phonehelper>()
val exs = ArrayList<phonehelper>()
phoneRecycler!!.layoutManager = LinearLayoutManager(Activity, LinearLayoutManager.HORIZONTAL, false). // activity returns null
...
I am getting Null value for
activity
wherever I put it, even in the OnCreateView, also this fragment is connected to a xml
3
Answers
I guess in your situation would be nice to replace logic from
OnCreateView
toOnActivityCreated
method. Cause in this method getActivity != null always.well I would suggest you to put
inside onViewCreated() method.
Also, your answer is Simple, use
EDIT:
Please Try This Code
If a fragment is no longer attached to an activity then the
activity
variable is going to be nullyou need to null check each time you try to use it