0

I have created a Fragment which is in ViewPager. Fragment is loading fine. I am using a button to swipe fragments in viewpager and before swiping, I want to check validations. So I did this in Activity :

val pos: Int = viewPager.currentItem
            val activeFragment: Fragment? = mAdapter.getItem(pos)
            if (viewPager.currentItem == 0) {

                if (pos == 0) (activeFragment as FragmentOne).checkValidation()

Below is my Fragment code.

class FragmentOne: BaseFragment() {

        fun newInstance(): FragmentOne{
            val args = Bundle()
            val fragment = FragmentOne()
            fragment.setArguments(args)
            return fragment
        }


        override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                                  savedInstanceState: Bundle?): View? {
            val view : View = inflater.inflate(R.layout.fragment_one, container, false);
            return view
        }

        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
        }

        override fun onActivityCreated(savedInstanceState: Bundle?) {
            super.onActivityCreated(savedInstanceState)
            initiateUI()
        }


        fun checkValidation(): Boolean {
            if (TextUtils.isEmpty(etDateOfBirth.text.toString())) {
                showMessage(etDateOfBirth, getString(R.string.str_empty_dob))
                return false
            }
            return true
        }
    }

When I press next I get error: java.lang.IllegalStateException: etDateOfBirth must not be null Can anyone help out?

Nir Patel
  • 357
  • 4
  • 17
  • Because `getItem` returns a NEW instance of the Fragment which is not added to your Activity and has no inflated layout. – EpicPandaForce Aug 06 '18 at 09:16
  • @EpicPandaForce what should I do to achieve my flow...?? Any workaround for it? – Nir Patel Aug 06 '18 at 09:50
  • @EpicPandaForce how will that work?? instantiateItem is deprecated and it does not return fragment.? Can you tell me how to use that.? Or give some reference may be – Nir Patel Aug 06 '18 at 09:59
  • Okay. See https://stackoverflow.com/questions/18609261/getting-the-current-fragment-instance-in-the-viewpager – EpicPandaForce Aug 06 '18 at 10:10
  • As EpicpandaForce already mentioned you can't simply call getItem(pos) because that would give you a **new** Fragment each time you call it. Instead you should use something like this https://gist.github.com/luksprog/183c31ca77dba4be8c9e891db24c2fae – user Aug 07 '18 at 07:46

1 Answers1

2

Didn't you define etDateOfBirth? Define edit text on onViewCreated()

EditText etDateOfBirth = view.findViewById(R.id.sample);
Ehsan Mashhadi
  • 2,568
  • 1
  • 19
  • 30