0

I have one activity and fragment inside, I open second activity for result from my fragment :

startActivityForResult(LocationSelectorActivity.newIntent(context!!), START_LOCATION_SELECTOR) 

If i force activity for die when user will leave it ( from developer option) , after back click from my second activity onViewCreated is called twice in my fragmetn

 override fun onViewCreated(view: View, savedInstanceState: Bundle?)

Here is how I add fragment :

 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        addFragment(MyFragment(), R.id.content_frame)
    }


fun AppCompatActivity.addFragment(fragment: Fragment, frameId: Int) {
    supportFragmentManager.inTransaction { add(frameId, fragment) }
}
Nininea
  • 2,671
  • 6
  • 31
  • 57
  • I'm not sure if I'm correctly following what you're saying, but are they separate instances? You're unconditionally adding a `Fragment` there without checking if one already exists. – Mike M. Aug 24 '18 at 09:50
  • actually I do, because it should be called only once for this activity – Nininea Aug 24 '18 at 09:52
  • If that's your actual code, then a new `Fragment` instance is added each time `onCreate()` runs. If the first `Activity` is being destroyed when you go to the second `Activity`, then the first `Activity` is being recreated when you go back, so `onCreate()` runs again, but the first `Fragment` instance is still attached to the `FragmentManager`. – Mike M. Aug 24 '18 at 09:58
  • 1
    AddFragment should only be called if saved instance state is null – EpicPandaForce Aug 24 '18 at 10:21
  • 1
    I would recommend just checking with the `FragmentManager` if the `Fragment` already exists. I realize that even Google's examples show that, but checking if `savedInstanceState` is null isn't a great solution, IMO, especially if you're going to end up juggling multiple `Fragment`s. It's best just to get in the habit of directly checking with `FragmentManager`. – Mike M. Aug 24 '18 at 10:37

1 Answers1

-2

The problem rises in following line:

startActivityForResult(LocationSelectorActivity.newIntent(context!!), START_LOCATION_SELECTOR)

LocationSelectorActivity.newIntent(context) must be replaced by:

Intent intent = new Intent(/*your desirable configiration*/);
getActivity().startActivityForResult(intent, START_LOCATION_SELECTOR);

or

Intent intent = new Intent(/*your desirable configiration*/);
startActivityForResult(intent, START_LOCATION_SELECTOR);

then in your host activity or the fragment override onActivityResult() method

Mahdi Rajabi
  • 582
  • 1
  • 4
  • 11